简体   繁体   English

为什么在对象键之后不能使用Javascript扩展运算符?

[英]Why can't Javascript spread operator be used after object key?

I have the following code: 我有以下代码:

const array = [{
    a: 'a',
    b: 'b'
  }];

  console.log(...array);

  const store = {
    obj: ...array
  }

console.log will print the results just fine. console.log会很好地打印结果。 However, when trying to set the key of store I get a Parsing error: Unexpected token . 但是,当尝试设置store密钥时,出现了Parsing error: Unexpected token

Isn't ...array a valid object to assign to the obj key of store ? ...array不是分配给storeobj键的有效对象吗?

... spreads out array into individual items. ...将阵列散布到各个项目中。 Array can have more than 1 element and hence there will be more than 1 RHS and that will be invalid. 数组可以包含1个以上的元素,因此将有1个以上的RHS,这将是无效的。 Hence, you can use obj : {...array} or obj : [...array] 因此,您可以使用obj : {...array}obj : [...array]

 const array = [{a: 'a',b: 'b'},{c: 'c', d: 'd'}]; console.log(...array); const store = { obj: {...array}, obj1: [...array] }; console.log(store); 

The spread syntax works inside of objects or iterable. 传播语法在对象内部起作用或可迭代。 In your case, you need to spread the elements within an array. 在您的情况下,您需要在数组中散布元素。

Spread Syntax 传播语法

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected , or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. 扩展语法允许将可迭代程序(例如数组表达式或字符串) 扩展到期望零个或多个参数(用于函数调用)或元素(用于数组文字)的位置 ,或将对象表达式扩展在零个或多个位置键值对(用于对象文字)是必需的。

 const array = [0, 1, 2] const store = { obj: [...array] // <-- the array is being spreded into an array. } console.log(store) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM