如何使用动态索引在JavaScript中更新数组?

5
让我们考虑一个数组:
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"]

是的,通过这样做,我添加了第四个属性,而第一个和第三个得到了更新?所以,这样可以吗?或者有更好的方法来执行上述任务吗?

提前致谢。


2
你考虑过使用forforeach循环吗? - Examath
2
这应该会有所帮助:https://dev59.com/VnM_5IYBdhLWcg3wcSx_ - moilejter
3个回答

3
如果你想在数组上调用它,可以添加一个原型函数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)


3
使用解构和剩余语法递归地完成此操作,以便在每次迭代中获取索引和项:

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循环,并跳过两个索引:

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);


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

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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接