小tips:JS操作数组的slice()与splice()方法

时间:2023-03-09 01:57:28
小tips:JS操作数组的slice()与splice()方法

slice(start, end)

slice()方法返回从参数指定位置开始到当前数组末尾的所有项。如果有两个参数,该方法返回起始和结束位置之间的项,但不包括结束位置的项。

var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4); console.log(colors2); // green, blue, yellow, purple
console.log(colors3); // green, blue, yellow

splice()有删除,插入,替换的功能

删除需要两个参数,要删除的第一项的位置和要删除的项数。

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

插入需要三个参数:起始位置、0(要删除的项数)和要插入的项

var colors = ["red", "green", "blue"];
var removed = colors.splice(1,0,"yellow", "orange");
console.log(colors); // ["red", "yellow", "orange", "green", "blue"]
console.log(removed); // 返回空

替换需要三个参数:起始位置、要删除的项数和要插入的任意数量的项。

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