arr.splice() 的含义
splice的中文释义为“拼接”,arr.splice() 即剪切掉数组中一个连续的片段后,再拼接上一个新片段。
arr.splice() 的语法
let newArr = arr.splice(起始索引index, 删除的个数, 新增元素1, 新增元素2...) // 返回被删除元素组成的新数组
会改变原数组
第三个及之后的参数表示:向原数组中添加新的元素,这些元素将会自动插入到开始位置索引的前面。
若未指定删除的个数,则从起始索引index到数组最后一个元素全部删除
arr.splice() 的使用
// 范例1 —— 从第index为1的位置开始,删除之后的所有元素 let arr1 = ["a", "b", "c", "d", "e", "f"]; let result1 = arr1.splice(1); arr1:["a"] result1:["b","c","d","e","f"]
//范例2 —— 删除最后两个元素 let arr = ["a", "b", "c", "d", "e", "f"]; let result = arr.splice(-2); arr:["a","b","c","d"] result:["e","f"]
//范例3 —— 从index为1的元素开始,一共删除三个元素 let arr = ["a", "b", "c", "d", "e", "f"]; let result = arr.splice(1, 3); arr:["a","e","f"] result:["b","c","d"]
//范例4 —— 从index为1的元素开始,一共删除三个元素,并且在 index=1 的前面追加两个元素 let arr = ["a", "b", "c", "d", "e", "f"]; let result = arr.splice(1, 3, "新增元素1", "新增元素2"); arr:["a","新增元素1","新增元素2","e","f"] result:["b","c","d"]
//范例5 —— E6语法实现数组合并-将arr2合并到arr1 let arr1 = ["a", "b", "c"]; let arr2 = ["1", "2", "3"]; arr1.splice(0, 0, ...arr2); arr1: [ '1', '2', '3', 'a', 'b', 'c' ]