数组的 splice , slice方法

发布于:2023-05-30 ⋅ 阅读:(245) ⋅ 点赞:(0)

splice 方法

结构1: 
arr.splice(start,deletedCount) 纯删除
从start下标开始,删除几个

结构2: 
arr.splice(start,deletedCount,item) 替换
从start下标开始,删除几个,并在该位置添加item

结构3: 
arr.splice(start,0,item) 纯添加
从start下标开始,删除0个,并在该位置添加item,start开始全部往后移动

let arr = [1,2,6,7,8];
arr.splice(2,0,3,4,5);//arr = [1,2,3,4,5,6,7,8];

slice 方法

该方法可以从数组中截取指定的字段,返回出来
返回值:返回截取出来的字段,放到新的数组中,不改变原数组

结构1:
arr.slice(start,end) ;从start下标开始截取,一直到end结束,不包括end

let arr = [0,1,2,3,4,5,6,7];
let newArr = arr.slice(0,3)//newArr = [0,1,2];

结构2:
arr.slice(start) ;从start下标开始截取,一直到最后

let arr = [0,1,2,3,4,5,6,7];
let newArr = arr.slice(2)//newArr = [2,3,4,5,6,7];

结构3:
arr.slice( ) ;全部截取

let arr = [0,1,2,3,4,5,6,7];
let newArr = arr.slice()//newArr = [0,1,2,3,4,5,6,7];