使用扩展语法时如何根据索引更新数组元素?

How to update an element of an array based on the index when using spread syntax?

将数组视为

const foo = [1, 2, 3];

现在,如果我想替换第二个元素,我可以这样做:

foo[1] = 4;

foo.splice(1,1,4);

const foo = [1, 2, 3];

console.log([...foo.slice(0, 1), 4, ...foo.slice(2)]);
// I know this creates a new array unlike the above two ways.

但是当我们使用扩展运算符进行浅层复制对象时,我们可以动态覆盖 属性,例如:

const someObject = {
 a: 1,
 b: 2,
 c: 3
}
const propertyToChange = 'b';

const newObject = { ...someObject, [propertyToChange]: 4 };

那么,是否有与此等效的数组?也许像下面这样根据索引更改元素。

const newArray = [...oldArray, [dynamicIndex]: 4 ];

排序:您可以使用 Object.assign:

const newArray = Object.assign([...oldArray], {[dynamicIndex]: 4});
// Or
const newArray = Object.assign([], oldArray, {[dynamicIndex]: 4});

之所以可行,是因为数组是对象。

实例:

const oldArray = [1, 2, 3, 4, 5, 6];
const dynamicIndex = 3; // The fourth entry
const newArray = Object.assign([], oldArray, {[dynamicIndex]: "four"});
console.log(newArray);