您的位置:首页 > Web前端 > JavaScript

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

2017-03-27 22:08 731 查看

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"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: