首页 > 解决方案 > 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", "x", "t"])。是否与不同的JS版本有关?

注意:这两个结果都是在运行 webpack 开发服务器后提取的。

标签: javascriptecmascript-6destructorecmarest-parameters

解决方案


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

"use strict";

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

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

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

推荐阅读