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

后端 未结 12 1905
余生分开走
余生分开走 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 15:53

    • Array.forEach “executes a provided function once per array element.”

    • Array.map “creates a new array with the results of calling a provided function on every element in this array.”

    So, forEach doesn’t actually return anything. It just calls the function for each array element and then it’s done. So whatever you return within that called function is simply discarded.

    On the other hand, map will similarly call the function for each array element but instead of discarding its return value, it will capture it and build a new array of those return values.

    This also means that you could use map wherever you are using forEach but you still shouldn’t do that so you don’t collect the return values without any purpose. It’s just more efficient to not collect them if you don’t need them.

提交回复
热议问题