如何使用索引动态更新javascript中的数组



让我们考虑一个数组:

var a = ["one", "two", "three"];

现在,要更新阵列,我必须执行以下操作:

a[0] = "1";
a[1] = "2";
a[2] = "3";

但是,如果数组更大,我就不能重复这个了。我想要一个函数,有了它的帮助,我可以这样做:

a.update(0, "1", 2, "3", 3, "4"); // => ["1", "two", "3", "4"]

是的,你看到了,在这个帮助下,我添加了第四个属性,而第一个和第三个属性得到了更新?那么,这是可以制作的吗?或者有更好的方法来执行上面的任务?

提前感谢

您可以递归地执行此操作,使用析构函数和rest语法在每次迭代中获取索引和项:

const a = ["one", "two", "three"];
const update = (arr, idx, itm, ...rest) => {
arr[idx] = itm;
if(rest.length)
update(arr, ...rest);
}
update(a, 0, "1", 2, "3", 3, "4")
console.log(a);

或者,您可以使用for循环,一次跳过2个索引:

const a = ["one", "two", "three"];
const update = (arr, ...rest) => {
for(let i = 0; i < rest.length; i+=2) {
const idx = rest[i];
const itm = rest[i+1];
arr[idx] = itm;
}
}
update(a, 0, "1", 2, "3", 3, "4")
console.log(a);

如果要在数组上调用它,可以添加一个prototype函数。不过,我会使用一个对象作为参数,每个键都对应一个索引。

var a = ["one", "two", "three"];
Array.prototype.update = function(args) {
for (var key in args) {
this[key] = args[key];
}
return this;
};
a.update({ 0:"1", 2:"3", 3:"4" })
console.log(a)

您可以这样做,使用对象参数的键值对来更新第一个参数中的数组。

var a = ["one", "two", "three"];
const update = (arr, changes) => {
for(k in changes) {
arr[k] = changes[k];
}
};
update(a, { 0: '1', 2: '3', 3: '4' });
console.log(a);

最新更新