JavaScript中的Map和ForEach有什么区别?
![46de19e9e568cc22a2cd5f240f2401e1.png](https://img-blog.csdnimg.cn/img_convert/46de19e9e568cc22a2cd5f240f2401e1.png)
如果你使用JavaScript
一段时间了,你可能遇到两个相似的数组方法:Array.prototype.map()
和Array.prototype.forEach()
。
那么,它们有什么不同?
Map & ForEach 定义
我们先看一眼它们在MDN上的定义:
- forEach() -- 对数组中的每个元素执行提供的函数
- map() -- 在被调用的数组基础上创建一个新数组,并对数组中的每个元素执行方法
这到底意味着什么?
嗯,forEach
方法实际上没有返回什么东西(undefined)。它只是简单为数组中的每个元素提供一个方法。允许该回调方法改变调用的数组。
译者加
javascript let arr = [1, 2, 3] arr.forEach((item, index)=> { arr[index] = item * 3 }) console.log(arr) // [3, 6, 9]
相似的,map()
也为数组中的每个元素都提供