JavaScript中forEach()和map()的相同点和区别

    技术2025-06-09  25

    相同点

    都是循环遍历数组中的每一项

    每一次执行匿名函数都支持三个参数,数组中的当前项item,当前项的索引index,原始数组array

    匿名函数中的this指向外层函数的this;当没有外层函数的时候,外层函数就是window

    只能遍历数组

    不同点

    forEach()方法不会返回执行结果,而是undefined

    forEach()会修改原来的数组map()方法会得到一个新的数组并返回

    两者用法

    1.foreach()

    没有返回值

    var array = [10,34,57,43,76]; var res = array.forEach(function (item,index,array) { array[index] = item*10; }) console.log(res);//--> undefined; console.log(array);//--> 通过数组索引改变了原数组;

    jquery中遍历:

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

    $.each(arr,function(index,value){ xxxx })

    2.map()

    返回一个新数组

    var array = [10,34,57,43,76]; var res = array.map(function (item,index,input) { return item*10;   }) console.log(res); //-->[100,340,570,430,760] console.log(array); //-->不变

    jquery中遍历:

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

    $.map(arr, function(value, index){   xxx   return XXX })

     

    Processed: 0.019, SQL: 9