使用等价于扩展语法的 Object.assign 按索引更新数组项

Updating array item by index using Object.assign equivalent in spread syntax

我最近在尝试更新数组索引时偶然发现了这个 gem;

我试过的是:

const a = [1,2,3];
Object.assign([...a], {1: 10}) );
// [1, 10, 3]

这允许我以编程方式更新特定数组项的值,而不是在一行中更新原始值。

然而,当我尝试将其转换为传播语法时:

[...a, ...{1: 10}]

它实际上没有工作,给我一个错误:

Uncaught TypeError: {(intermediate value)} is not iterable

假设对象分配向对象添加了一个可迭代原型,使第一个选项起作用,而传播语法更通用并且不包含此功能,我是否正确?

谢谢

你不能那样传播对象。参考这个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/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.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Object.assign() 方法需要一个 Object - 它不必是可迭代的。

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

可迭代对象https://javascript.info/iterable

所以这似乎与您的建议完全相反:扩展语法 不如 Object.assign() 方法,因为它需要更严格的项目类型才能正常工作。