使用 JavaScript 實現類似於 Array.prototype.includes() 方法的自定義函式


問題

我們需要編寫一個 JavaScript 函式,該函式位於 Array 的原型物件上。它必須接受一個字面值,如果該值存在於呼叫該函式的陣列中,則返回 true,否則返回 false。

示例

程式碼如下:

 即時演示

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const num = 6;
Array.prototype.customIncludes = function(num){
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(num === el){
         return true;
      };
   };
   return false;
};
console.log(arr.customIncludes(num));

輸出

true

更新於:2021 年 4 月 17 日

967 次瀏覽

為你的 事業助力

完成課程,獲得認證

開始吧
廣告
© . All rights reserved.