駐留在 Array 類的原型物件上的 JavaScript 函式


問題

我們需要編寫一個駐留在 Array 類的原型物件上的 JavaScript 函式。此函式應採用回撥函式,並且該函式應該返回第一個使得回撥函式返回 true 的元素。

我們需要將當前元素和當前索引作為第一個和第二個引數傳遞給回撥函式。

示例

以下程式碼展示了函式的編寫:-

 演示

const arr = [4, 67, 24, 87, 15, 78, 3];
Array.prototype.customFind = function(callback){
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(callback(el, i)){
         return el;
      };
      continue;
   };
   return undefined;
};
console.log(arr.customFind(el => el % 5 === 0));

輸出

15

更新於: 2021-04-19

75 次瀏覽

開啟您的職業生涯

完成課程獲得認證

立即開始
廣告