forEach():循环遍历,for(){}的增强版
在数组中,被封装好的方法,可以直接arr.forEach()使用
利用for循环实现一个myForEach
代码如下:
var arr=["hello",12,null,undefined];
Array.prototype.myForEach=function(){
if(typeof arguments[0]=='function'&&arguments.length==1){//存在一个参数并且第一个参数为一个function
for(i=0;i<this.length;i++){//循环遍历数组项
arguments[0].call(window,this[i],i,this)
}
}else if(arguments==2){//存在两个参数,一个为function函数,第二个为this
for(i=0;i<this.length;i++){
arguments[0].call(arguments[1],this[i],i,this)
}
}
}
arr.myForEach(function(item,index,arr){
console.log(this);
console.log(item,index,arr)
})