函数特点
- 基于当前数组创建一个新数组并返回【浅拷贝】
- 切片范围是[n, m)【不包括结束位置】
- end参数可选,不填则默认到数组最后一项
- start参数可选,不填则默认浅拷贝整个数组
- 可接受负数参数,则从数组倒数第N个开始切,倒数第M个前结束
函数用法
Array.prototype.slice(start[, end])
使用场景
const ary = [{ num: 1 }, { num: 2 }, { num: 3 }];
ary.slice(0, 1); // [{ num: 1 }]
ary.slice(0); // [{ num: 1 }, { num: 2 }, { num: 3 }]
ary.slice(); // [{ num: 1 }, { num: 2 }, { num: 3 }]
function toArray() {
return Array.prototype.slice.call(arguments);
}
toArray('1', '2', '3', '4', '5');
const elements = document.querySelectorAll('p');
console.log(elements);
Array.prototype.slice.call(elements);
手写实现
Array.prototype.mySlice = function(start = 0, end = this.length) {
// if (start && end) {
start = start < 0 ? start = this.length + start : start
end = end < 0 ? end = this.length + end : end
// }
// if (!start) start = 0
// if (!end) end = this.length
const res = []
for (let i = start
res.push(this[i])
}
return res
}