如何在 JavaScript 中使用包裝對陣列進行切片


假設我們需要編寫一個替代預設 Array.prototype.slice() 的陣列方法。通常,Array.prototype.slice() 方法會接收兩個引數,分別是起始索引和結束索引,並返回一個從起始索引到結束索引-1 的原始陣列的子陣列。

我們的目的是讓 slice() 方法返回一個從起始索引到結束索引的子陣列,而不是結束索引-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
]

更新於:20-Aug-2020

292 次瀏覽

開啟您的 職業

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.