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