JS 字符串解构:rest 参数返回不一致的数据

问题描述

考虑以下示例

一个旧项目:

const [x,...y] = "text";
console.log(x) // "t"
console.log(y) // "ext"

一个基于 CRA 的新项目:

const [x,...y] = "text";
console.log(x) // "t"
console.log(y) // ["e","x","t"]

我不确定为什么 y 会为旧项目返回一个字符串 ("ext"),而对于新项目,它是一个字符数组 (["e","t"])。是不是跟JS版本不同有关?

注意:两个结果都是在运行 webpack dev server 后提取的。

解决方法

babel website中,您可以看到您基于 es2015-loose 的代码转换为此代码,因此此代码的输出与您的旧项目相同

"use strict";

var _text = "text",x = _text[0],y = _text.slice(1);

console.log(x); // "t"

console.log(y); // "ext"