forEach与filter功能的实现
文章目录
//forEach的实现
Array.prototype.myForEach = function (fn){
if((typeof fn).toLowerCase() != 'function'){
throw new TypeError('must be function')
}
let i
for(i = 0; i < this.length; i++){
fn(this[i],i,this)
}
}
const arr = [1,4,5]
arr.myForEach((item,index,arr)=>{
console.log(item,index,arr)
})
//filter的实现
Array.prototype.myFilter = function (fn) {
if( (typeof fn).toLowerCase() != "function" ){
throw new TypeError('must be function')
}
var arr = this
arrs = []
for(var i = 0; i < arr.length; i++){
var val = arr[i]
if(fn.call(null , val,i,arr)){
arrs.push(val)
}
}
return arrs
}
var arr = [1,2,3,4,5,6]
const as = arr.myFilter((item,index,arr)=>{
return item>2
})
console.log(as)

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论