Array.prototype.slice()

81 阅读1分钟

函数特点

  • 基于当前数组创建一个新数组并返回【浅拷贝】
  • 切片范围是[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'); // ['1', '2', '3', '4', '5']

// NodeList【文档中提取的节点集合】
const elements = document.querySelectorAll('p');
console.log(elements); // NodeList(1) [p.xxx, p.xxx]
Array.prototype.slice.call(elements); // [p.xxx, p.xxx]

手写实现

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; i < end; i++) {
        res.push(this[i]);
    }
    return res;
}