使用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP