js 的 slice
和 splice
都是数组的方法
-
slice
不改变原数组
-
splice
改变原数组
let arr = [1, 2, 3, 4, 5]
// slice(start?: number, end?: number): T[];
// start 和 end 表示索引
// slice(start[, end]) [start, end) 左闭右开区间
// 返回值是新的数组, 注意原数组不变
console.log(arr.slice(1, 4));
// splice(start, deleteCount, ...items) items 表示在 start 位置插入元素
// start 表示要删除的开始索引, deleteCount 表示要删除的元素数量, items 表示插入到 start 位置的元素数组
// 返回值是被删除的元素数组
console.log(arr.splice(1, 2, 'a', 'b', 'c'));
// 注意原数组内容已经被永久改变
console.log(arr);