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

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

我们希望做的是让这个slice()函数像这样它返回一个从索引开始到结束而不是结束 1 的子数组。因此,执行此操作的代码如下所示。我们使用 for 循环遍历数组,这实际上比我们拥有的任何数组方法都快。然后返回所需的子数组,最后我们覆盖数组。使用我们刚刚编写的方法 -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

]

以上是 如何在 JavaScript 中使用包装对数组进行切片 的全部内容, 来源链接: utcz.com/z/335662.html

回到顶部