[removed] Difference between .forEach() and .map()

后端 未结 12 1906
余生分开走
余生分开走 2020-11-22 15:19

I know that there were a lot of topics like this. And I know the basics: .forEach() operates on original array and .map() on the new one.

I

12条回答
  •  遇见更好的自我
    2020-11-22 16:01

    Difference between forEach() & map()

    forEach() just loop through the elements. It's throws away return values and always returns undefined.The result of this method does not give us an output .

    map() loop through the elements allocates memory and stores return values by iterating main array

    Example:

       var numbers = [2,3,5,7];
    
       var forEachNum = numbers.forEach(function(number){
          return number
       })
       console.log(forEachNum)
       //output undefined
    
       var mapNum = numbers.map(function(number){
          return number
       })
       console.log(mapNum)
       //output [2,3,5,7]
    

    map() is faster than forEach()

提交回复
热议问题