如何在 JavaScript 中使用包装对数组进行切片

javascriptweb developmentobject oriented programming更新于 2025/9/30 2:20:17

假设,我们需要编写一个数组方法来覆盖默认的 Array.prototype.slice()。通常,Array.prototype.slice() 方法接受两个参数:起始索引和结束索引,并返回从索引 start 到 end-1 的原始数组的子数组。

我们希望使此slice() 函数像这样,以便它返回从索引 start 到 end 而不是 end-1 的子数组。因此,执行此操作的代码如下所示。我们使用 for 循环对数组进行迭代,这实际上比我们拥有的任何数组方法都快。然后返回所需的子数组,最后我们用刚刚编写的方法覆盖 Array.prototype.slice() −

示例

const arr = [5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9];
const slice = function(start = 0, end = this.length-1){
   const part = [];
   for(let i = start; i <= end; i++){
      part.push(this[i]);
   };
   return part;
};
Array.prototype.slice = slice;
console.log(arr.slice(0, 4));
console.log(arr.slice(5, 8));
console.log(arr.slice());

输出

控制台中的输出将是 −

[ 5, 5, 34, 43, 43 ]
[ 76, 78, 3, 23 ]
[
   5, 5, 34, 43, 43, 76,
   78, 3, 23, 1, 65, 87,
   9
]

相关文章


有用资源