为什么不能在对象键后使用 Javascript 展开运算符?
Why can't Javascript spread operator be used after object key?
我有以下代码:
const array = [{
a: 'a',
b: 'b'
}];
console.log(...array);
const store = {
obj: ...array
}
console.log
将打印结果就好了。但是,当尝试设置 store
的密钥时,我得到了 Parsing error: Unexpected token
。
...array
不是分配给 store
的 obj
键的有效对象吗?
...
将数组展开为单个项目。数组可以有超过 1 个元素,因此会有超过 1 个 RHS,这将是无效的。因此,您可以使用 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);
扩展语法适用于对象或可迭代对象。在您的情况下,您需要将元素散布在一个数组中。
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)
我有以下代码:
const array = [{
a: 'a',
b: 'b'
}];
console.log(...array);
const store = {
obj: ...array
}
console.log
将打印结果就好了。但是,当尝试设置 store
的密钥时,我得到了 Parsing error: Unexpected token
。
...array
不是分配给 store
的 obj
键的有效对象吗?
...
将数组展开为单个项目。数组可以有超过 1 个元素,因此会有超过 1 个 RHS,这将是无效的。因此,您可以使用 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);
扩展语法适用于对象或可迭代对象。在您的情况下,您需要将元素散布在一个数组中。
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)