【问题标题】:Spread operator with bracket notation [duplicate]带括号符号的扩展运算符[重复]
【发布时间】:2020-01-13 09:58:10
【问题描述】:

以下工作正常:

const o = {one:1,two:2,three:3};
const {one,...others}=o;//one=1, others={two:2,three:3}

但是我该怎么做:

var o = {['this-is-one']:1,two:2,three:3};
var {['this-is-one'],...others}=o;

目前这给了我一个 SyntaxError: Unexpected token ','

我怀疑它不起作用,因为this-is-one 对于常量名称无效(它仅适用于属性值)。

【问题讨论】:

  • 给它一个别名{'this-is-one':one,...others}=o;
  • [] 仅用于计算的属性名称。正如上面评论中提到的,在创建或解构对象时不需要它
  • @adiga,需要拉出不符合变量名的属性。
  • @NinaScholz 我的意思是 [] 不需要包装器。 var o = { 'this-is-one':1,two:2,three:3}; var {'this-is-one':one,...others}=o 就够了
  • @adiga,对不起,你是对的。 ;-)

标签: javascript ecmascript-6


【解决方案1】:

您需要重命名变量名,因为给定的键不是有效的变量名。

var o = { 'this-is-one': 1, two: 2, three: 3 },
    { 'this-is-one': thisIsOne, ...others } = o;

console.log(thisIsOne);
console.log(others);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-17
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2017-08-15
    • 2015-09-24
    相关资源
    最近更新 更多