4

我很好奇为什么这似乎是不可能的:

const {a, b, 'special-one'} = { a:1, b:2, 'special-one': 3 };
// output => missing : after property id

是否有可能在未来的 ES 版本中找到该语法?

谢谢你的灯:)

4

2 回答 2

6

在解构语句中重命名变量,您不能在名称中包含带有连字符的变量。您可以使用以下语法重命名,请参阅MDN:分配给新变量名

属性可以从对象中解压缩并分配给名称与对象属性不同的变量。

const {
  a,
  b,
  'special-one': specialOne
} = {
  a: 1,
  b: 2,
  'special-one': 3
};

console.log(specialOne);

于 2019-06-05T13:42:59.910 回答
3

special-one不能是变量名。所以你需要另一个名字 like specialOne:在新变量名的键名之后使用。

const {a, b, 'special-one':specialOne} = { a:1, b:2, 'special-one': 3 };
console.log(specialOne)

在上述情况下,您有一个纯字符串作为键名。但是,如果有一个表达式,您将需要使用[]

let keyName = 'special-one'

const {a, b, [keyName]:specialOne} = { a:1, b:2, 'special-one': 3 };
console.log(specialOne)

于 2019-06-05T13:42:43.393 回答