让我们考虑一个数组:
var a = ["one", "two", "three"];
Run Code Online (Sandbox Code Playgroud)
现在,要更新数组,我必须执行以下操作:
a[0] = "1";
a[1] = "2";
a[2] = "3";
Run Code Online (Sandbox Code Playgroud)
但如果数组更大,我就无法重复此操作。我想要一个函数,借助它,我可以这样做:
a.update(0, "1", 2, "3", 3, "4"); // => ["1", "two", "3", "4"]
Run Code Online (Sandbox Code Playgroud)
是的,您看到在这个帮助下我添加了第四个属性,而第一个和第三个属性得到了更新?那么,这个可以制作吗?或者有更好的方法来执行上述任务?
提前致谢
您可以递归地执行此操作,使用解构和其余语法在每次迭代时获取索引和项目:
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);Run Code Online (Sandbox Code Playgroud)
或者,您可以使用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);Run Code Online (Sandbox Code Playgroud)