在 JavaScript 中實現自定義函式,如 Array.prototype.filter() 函式


問題

我們需要編寫一個存在於 Array 類的原型物件中的 JavaScript 函式。

我們的函式應將回調函式作為其唯一的引數。此回撥函式應為陣列的每個元素呼叫。

此回撥函式應有兩個引數,即對應的元素及其索引。如果回撥函式返回 true,我們應將對應的元素包含在輸出陣列中,否則應將其排除在外。

示例

程式碼如下 −

 即時演示

const arr = [5, 3, 6, 2, 7, -4, 8, 10];
const isEven = num => num % 2 === 0;
Array.prototype.customFilter = function(callback){
   const res = [];
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(callback(el, i)){
         res.push(el);
      };
   };
   return res;
};
console.log(arr.customFilter(isEven));

輸出

[ 6, 2, -4, 8, 10 ]

更新於: 21-Apr-2021

829 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

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