24.原生的forEach和自我实现的forEach方法

Array对象原生的forEach

  • forEach方法会自动调用传入的函数,每次调用都会将当前遍历到的元素和当前遍历到的索引,和当前被遍历的数组传递给这个函数
1
2
3
4
arr.forEach(function (currentValue, currentIndex, currentArray){

console.log(currentValue);
});

自定义的forEach方法

1
2
3
4
5
6
7
8
9
10
Array.prototype.myForEach = function (fn) {
// this === [1, 3, 5, 7, 9]
for(let i = 0; i < this.length; i++){
fn(this[i], i, this);
}
};
arr.myForEach(function (currentValue, currentIndex, currentArray)
{
console.log(currentValue, currentIndex, currentArray);
});

思路:

  • 在Array.prototype.myForEach上,函数参数是一个函数,this是调用这个方法的arr,fn是遍历处理arr元素的函数
  • 在arr调用myForEach时传进去处理arr元素的函数
  • 将arr.myForEach中的函数抽出来,只传函数名会比较清晰,即
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Array.prototype.myForEach = function (fn) {
    // this === [1, 3, 5, 7, 9]
    for(let i = 0; i < this.length; i++){
    fn(this[i], i, this);
    }
    };
    var deal=function (currentValue, currentIndex, currentArray)
    {
    console.log(currentValue, currentIndex, currentArray);
    }
    arr.myForEach(deal);

总结:自定义foreach

  • 原型对象上,函数需要遍历arr
  • 处理数组的函数作为参数传到原型对象上的foreach函数