forEach和map区别在哪里知道吗?
// forEach
Array.prototype.forEach(callback(item, index, thisArr), thisArg) // map
Array.prototype.map(callback(item, index, thisArr), thisArg)
大致看一下,感觉参数都一样,都是用于循环.
他们之间的区别在于,map的callback是可以return的,但forEach并不可以.
map
方法会给原数组中的每个元素都按顺序调用一次callback
函数。callback
每次执行后的返回值(包括undefined
)组合起来形成一个新数组。callback
函数只会在有值的索引上被调用;那些从来没被赋过值或者使用delete
删除的索引则不会被调用。
好,我们来看一个例子
// 快速生成1-100的数组 let res = Array.from(new Array(100)).map((x,y) => y) res // [1,2,3,4..., 100]
如果将map换成forEach
let res = Array.from(new Array(100)).forEach((x, y) => y) 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