ES5中, map 和 forEach的区别

forEach和map区别在哪里知道吗?

1 // forEach
2 Array.prototype.forEach(callback(item, index, thisArr), thisArg)
3 
4 // map
5 Array.prototype.map(callback(item, index, thisArr), thisArg)


大致看一下,感觉参数都一样,都是用于循环.

他们之间的区别在于,map的callback是可以return的,但forEach并不可以.

map 方法会给原数组中的每个元素都按顺序调用一次  callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组。 callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。


好,我们来看一个例子

1 // 快速生成1-100的数组
2 
3 let res = Array.from(new Array(100)).map((x,y) => y) 
4 
5 res  // [1,2,3,4..., 100]

 

如果将map换成forEach

1 let res = Array.from(new Array(100)).forEach((x, y) => y)
2 
3 res // undefined

 

forEach() 为每个数组元素执行一次 callback 函数;与 map() 或者 reduce() 不同的是,它总是返回 undefined 值

因为forEach的callback没有返回值,所以forEach循环不能执行  链式操作.

所以如果要使用map或forEach循环的话,可以考虑下面的建议

因为map生成一个新数组,当你不打算使用返回的新数组却使用map是违背设计初衷的,请用forEach或者for-of替代。你不该使用map:

A)你不打算使用返回的新数组,或/且 B) 你没有从回调函数中返回值。

 

摘要: 
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

posted @ 2020-02-20 17:18  军君  阅读(292)  评论(0)    收藏  举报