在 JavaScript 中实现像 Array.prototype.filter() 函数这样的自定义函数
问题
我们需要编写一个基于Array类的原型Object的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 ]