经常使用filter
函数,想了解一下如何手动实现相似的效果,于是自己学习封装了一下,前端学习之路,永不停歇
Array.prototype.filter2 = function (fn) {
if (typeof fn !== "function") {
throw new TypeError(`${fn} is not a function`);
}
let newArr = [];
for(let i=0; i< this.length; i++) {
fn(this[i]) && newArr.push(this[i]);
}
return newArr;
}
let arr = [1,2,3,4,5];
let arr2 = arr.filter2(function(item){
return item != 1
})
console.log(arr2) // [2,3,4,5]