slice 工作原理
slice是数组上的一个方法,它最多有两个参数:
arr.slice([begin[,end]])
begin
从该索引处开始提取原数组中的元素,如果该参数为负数,则表示从原数组中的倒数第几个元素开始提取,slice(-2) 表示提取原数组中的倒数第二个元素到最后一个元素(包含最后一个元素)。
如果省略 begin ,则 slice 从索引0开始。
end
在该索引处结束提取原数组元素(从0开始)。slice 会提取原数组中索引从 begin 到 end 的所有元素(包含begin,但不包含 end)。
基本用法
用法1:简单的复制
const arr1 = arr.slice();
没有任何参数的slice 执行的是一个简单的浅拷贝。
用法2:获取从 n 开始的子数组
使用slice 方法最简单的方法就是原始数组从 n 开始抽取的所有元素。
一种情况是希望弹出数组的第一个元素并使用它,返回剩余的数组,但希望在不修改原始数组的情况下执行。
funciton useone (arr){
const usedItem = arr[0];
return arr.slice(1);
}
用法3:获取从末尾 n 开始的子数组
slice的另一个使用方法是获取数组的末尾,利用的是 负索引 从末尾开始计数。
const last = arr.slice( -3 );
用法4:获取数组的前 n 个
由于JavaScript数组是从0开始的(索引从0开始),这使得获取前 n 个元素变得非常简单:
const arr4 = arr.slice( 0 , 4 );
用法5:获取数组中的某段子数组
function pullSegment ( arr, begin , length ) {
return arr.slice( begin, begin + length );
}
处理类似数组的对象
slice 方法也可用于类似数组的对象。
如arguments、NodeLists。
要在类似数组的对象上使用slice方法,需要直接从 Array.prototype引用它,如下所示:
Array.prototype.slice.call( arguments );
用法6:将类似数组的对象转换为数组
转换为数组,是为了方便使用数组方法,否则类数组是不能使用数组的方法的。
const args = Array.prototype.slice.call( arguments );
用法7:将任意长度多余的参数强制转换为数组
function myFunc (a ,b ) {
const extraArr = Array.prototype.slice.call( arguments , 2);
}
这允许使用任意数量的参数调用myFunc,如:
myFunc(1,2,3,4,5,6,7,8);
在函数里面会得到 a == 1 , b===2, extraArr ===[3,4,5,6,7,8];
用法8:修改数组中特定索引
function replaceIndex ( arr ,index , newVal) {
return [
...arr.slice(0 , index),
newVal,
...arr.slice(index + 1 )
];
}