forEach()有两个参数,一个为回调函数,第二个为this,this参数可以不写,当只有一个参数时,this->window;当有第二个参数时,this->第二个参数。
参数:
回调函数 this:当前回调函数中所指的对象
回调函数:
参数:
item index arr
数组元素 下标 arr
item:每次循环所获取的数组元素
index:每次循环的数组元素所对应的数组下标
arr:当前循环的数组
自定义源码:
var arr=[1,2,3,4];
var arr1=[1,2];
Array.prototype.myForEach=function(){ //声明myForEach()
if(arguments.length==1 && typeof arguments[0]=='function'){
for(var i=0;i<this.length;i++){
arguments[0].call(window,this[i],i,this); //调用回调函数,此处令arguments[0](下面的回调函数)方法的this(71行的this)-->window是因为原函数forEach()中当只有一个参数(回调函数)时,回调函数的this-->window,所以此处是为了还原this指向
//console.log(this);//此处的this指向调用myForEach()方法的arr
}
}else if(arguments.length==2){
//arguments[0]:回调函数
//arguments[1]:由this指向
for(var i=0;i<this.length;i++){
arguments[0].call(arguments[1],this[i],i,this)//调用回调函数,此处令arguments[0](下面的回调函数)方法的this(71行的this)-->arguments[1]是因为原函数forEach()中当第二个参数时,回调函数的this-->第二个参数(arguments[1]),所以此处是为了还原this指向
//console.log(this); 此处的this指向调用myForEach()方法的arr
}
}
}
arr.myForEach(function(item,index,arr){ //调用myForEach(),参数为声明回调函数
console.log(item,index,arr);
console.log(this);
},[]);
如何写函数源码:
1、声明函数
2、判断参数个数及类型
3、如何循环执行回调函数
4、回调函数中的this值指向