js splice()方法

splice()方法有3中方法:

1.删除:可以删除任意数量的项,只要指定两个参数:要删除的第一项的位置和删除的项数。例如:splice(0,2)会删除数组中的前两项。

var colors=["red","green","blue","black","white"];
colors.splice(0,2);
console.log(colors);
// ["blue", "black", "white"]

2.插入:可以向指定的位置插入任意数量的项,需要3哥参数:起始位置、0(要删除的项数)和要插入的项。;例如:splice(2,0,"red","green")

var colors=["red","green","blue","black","white"];
colors.splice(1,0,"orange");
console.log(colors);
// ["red", "orange", "green", "blue", "black", "white"]

3.替换:可以向指定位置插入任意数量的项,且同时删除任意数量的项。需要3哥参数:起始位置、要删除的项数和要插入的项。;例如:splice(2,1,"red","green")

var colors=["red","green","blue","black","white"];
colors.splice(1,1,"orange");
console.log(colors);
// ["red", "orange", "blue", "black", "white"]


你可能感兴趣的:(前端)