forEach 和 map 的区别。
定义
返回值
连锁能力
何时使用map()?何时使用forEach()?
最后想说的话
JavaScript 提供了一些方便的数组迭代方法。最常用的两个方法是 `__instance__` 和 ` Array.prototype.forEach()__instance__` Array.prototype.map()。虽然都可以使用这两种方法迭代数组,但输出结果不同。对于很多开发者,尤其是初学者来说,这些方法并不清晰易懂。
定义
该方法每次map()都会创建一个新数组,其中包含对调用数组中的每个元素调用提供的函数所得到的填充结果。
该forEach()方法对数组中的每个元素执行一次提供的函数。
返回值
map()和 的主要区别在于forEach()返回值。map 返回一个新数组,其中包含根据你编写的函数转换后的元素,即使它们执行相同的操作,返回值也是undefined。
let users=["jyothiprakash","bhanu","nikitha"]
const newArray=users.map((d)=>{
return {_id:d}
})
//>>>>[{_id: "jyothiprakash"},{_id: "bhanu"},{_id: "nikitha"}]
const newArray=users.forEach((d)=>{
return {_id:d}
})
//>>>>>>>>>>>>>return value: undefined
连锁能力
map()`and` 和 ` or`的区别在于前者forEach()可以与其他方法链式调用。`is`map可以链式调用,而 ` forEachis` 则不能。
这意味着 map 可以与其他方法(例如 `map` reduce()、sort()`forEach` 等)链式调用。但对于 `forEach` 来说,这是不可能的,因为它会返回 undefined。
let data=[1,2,3,4,5]
let res=data.map((d)=>d*2).reduce((total,value)=>total+value)
// return value:30
let res=data.forEach((d)=>d*2).reduce((total,value)=>total+value)
//Cannot read properties of undefined (reading 'reduce')"
何时使用map()?何时使用forEach()?
选择使用 forEach 还是 map 取决于你的具体使用场景。
如果你想更改、替换或使用数据,你可以选择,map因为它会返回一个新的数组。
如果你不想返回数组,你可以使用forEach循环for。
最后想说的话
1.几乎任何你能想到的方法forEach()和map()技巧。
2.map 分配内存并始终存储return值。forEach 丢弃返回值并始终返回undefined。
3. forEach 允许回调函数修改当前数组,但 map 不会修改当前数组,而是返回新数组。
我希望这篇文章能阐明 map 和 forEach 方法之间的区别。如果还有其他方法需要区分,请在评论区留言。
如果这篇文章对您有帮助,请点击❤️标签。
谢谢。
文章来源:https://dev.to/jyothiprakashk/difference- Between-foreach-and-map-2674