js数组中foEach和map的用法详解 jq中的$.each和$.map

数组中foEach和map的用法详解

相同点:

1.都是循环遍历数组(仅仅是数组)中的每一项。
2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项value,当前项的索引index,原始数组array。
3.匿名函数中的this都是指Window。
4.IE6-8不兼容,通过在数组原型上扩展此方法可以实现
形式:

[].forEach(function(value,inede,array) {
    //...
});
[].map(function(value,inede,array) {
    //...
});

Array.prototype.myForEach = function myForEach(callback,context){  
    context = context || window;  
    if('forEach' in Array.prototye) {  
        this.forEach(callback,context);  
        return;  
    }  
    //IE6-8下自己编写回调函数执行的逻辑  
    for(var i = 0,len = this.length; i < len;i++) {  
        callback && callback.call(context,this[i],i,this);  
    }  
}  

forEach():
参数:value数组中的当前项, index当前项的索引, array原始数组;
数组中有几项,那么传递进去的匿名回调函数就需要执行几次。
无返回值,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;

    var data = [1,23,45,56,7,8];
    data.forEach(function(value,index,arr) {
        arr[index] = arr[index]*10;
    });

map():
有返回值,可以return出来。
参数:value数组中的当前项,index当前项的索引,array原始数组;
区别:map的回调函数中支持return返回值;相当于把数组中的每一项改变(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);

    var data = [10,230,450,560,70,80];
    var data1 = data.map(function(value,index,arr) {
        return value/10;
    });
    console.log(data);
    console.log(data1);
//(6) [10, 230, 450, 560, 70, 80]
//(6) [1, 23, 45, 56, 7, 8]

jQuery中的$.each和$.map

相比于原生js功能有了扩展,可以遍历对象。
形式:

$.each(obj,function(index,value) {
    //...
});
$.map(obj,function(index,value) {
    //...
});

$.each()

没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项v。如果遍历的是对象,k 是键,v 是值。

$.each( { name: "assassin", age: 23 }, function(k, v){  
     console.log( "Key: " + k + ", Value: " + v );  
}); 
/*
Key: name, Value: assassin
Key: age, Value: 23
*/

$.map()

有返回值,可以return 出来。$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反:数组中的当前项v,当前项的索引i。如果遍历的是对象,k 是键,v 是值。

    $.map( { name: "assassin", age: 23 }, function(k, v){  
        console.log( "Key: " + k + ", Value: " + v );  
    });  
//Key: assassin, Value: name
//Key: 23, Value: age
原文地址:https://www.cnblogs.com/intelwisd/p/8521914.html