what use does the javascript forEach method have (that map can't do)?

前端 未结 8 1451
小鲜肉
小鲜肉 2020-12-04 07:24

The only difference I see in map and foreach is that map is returning an array and forEach is not. However, I don\'t even understand the last line

8条回答
  •  孤城傲影
    2020-12-04 07:46

    The essential difference between map and forEach in your example is that forEach operates on the original array elements, whereas map explicitly returns a new array as a result.

    With forEach you are taking some action with -- and optionally changing -- each element in the original array. The forEach method runs the function you provide for each element, but returns nothing (undefined). On the other hand, map walks through the array, applies a function to each element, and emits the result as a new array.

    The "side effect" with forEach is that the original array is being changed. "No side effect" with map means that, in idiomatic usage, the original array elements are not changed; the new array is a one-to-one mapping of each element in the original array -- the mapping transform being your provided function.

    The fact that there's no database involved does not mean that you won't have to operate on data structures, which, after all, is one of the essences of programming in any language. As for your last question, your array can contain not only numbers, but objects, strings, functions, etc.

提交回复
热议问题