JS:解析forEach()、map()源码及浅谈两者之间的区别

4,783 阅读1分钟

forEach()源码解析

var arr = [1, 2, 3, 4, 5]
Array.prototype.myForEach = function(fn){
    var len = this.length;
    for(var i = 0; i < len; i ++){
        //将元素传给回调函数
        fn(this[i],i);
    }
}
arr.myForEach(function (ele, index){
    console.log(ele, index);
})

map()源码解析

var arr = [1, 2, 3, 4, 5]
Array.prototype.myMap = function(fn){
    var len = this.length;
    //创建新数组
    var arr = [];
    for(var i = 0; i < len; i ++){
        arr.push(fn(this[i],i))
    }
    return arr;
}
var aa = arr.myMap(function(ele, index){
    return ele * 2;
})
console.log(aa);

相同点

1)都是循环遍历数组中的每一项;
2)forEach()map()匿名函数的参数相同,参数分别是item(当前每一项)、index(索引值)、arr(原数组);
3)this都是指向调用方法的数组;
4) 只能遍历数组;

不相同点

1)map()创建了新数组,不改变原数组;forEach()可以改变原数组。
2)遇到空缺的时候map()虽然会跳过,但保留空缺;forEach()遍历时跳过空缺,不保留空缺。
3map()按照原始数组元素顺序依次处理元素;forEach()遍历数组的每个元素,将元素传给回调函数。
1) 用forEach()为数组中的每个元素添加属性
var arr = [
    {name : 'kiwi', age : 12},
    {name : 'sasa', age : 22},
    {name : 'alice', age : 32},
    {name : 'joe', age : 42}
]
arr.forEach(function(ele, index){
    if(index > 2){
        ele.sex = 'boy';
    }else{
        ele.sex = 'girl';
    }
    return arr1
})
console.log(arr)//元素组发生改变
//[{name: "kiwi", age: 12, sex: "girl"},{name: "sasa", age: 22, sex: "girl"},{name: "alice", age: 32, sex: "girl"},{name: "joe", age: 42, sex: "boy"}]
2) 遇到空缺比较
['a', , 'b'].forEach(function(ele,index){
    console.log(ele + '. ' + index);
})
//0.a
//2.b
['a', , 'b'].map(function(ele,index){
    console.log(ele + '. ' + index);
})
//['0.a', , '2.b']