
forEach和map的区别
发布日期:2021-05-04 17:18:37
浏览次数:24
分类:精选文章
本文共 1327 字,大约阅读时间需要 4 分钟。
相同点
- 都是循环遍历数组中的每一项
- forEach和map方法里每次执行匿名函数都支持3个参数,参数分别是item(当前每一项)、index(索引值)、arr(原数组)
- 匿名函数中的this都是指向window
- 只能遍历数组
- 都有兼容问题
不同点
- map速度比foreach快
- map会返回一个新数组,不对原数组产生影响,foreach不会产生新数组,
- map因为返回数组所以可以链式操作,foreach不能
forEach循环(其中item为该索引下的值,index为索引,arr为数字本身,参数名可改变,但是顺序不能改变)
var arr = ['zxx', 18, 'smart', 'good'];arr.forEach(function(item,index,arr){ console.log(item); console.log(index); console.log(arr);});// zxx// 0// ["zxx", 18, "smart", "good"]// 18// 1// ["zxx", 18, "smart", "good"]// smart// 2// ["zxx", 18, "smart", "good"]// good// 3// ["zxx", 18, "smart", "good"]
forEach 中用 await 产生的问题
async function test () { let arr = [4, 3, 2, 1] arr.forEach(async item => { const res = await handle(item) console.log(res) }) console.log('结束')}function handle (x) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(x) }, 1000 * x) })}test()
我们期望的结果是: 4 3 2 1 结束
但是实际上会输出: 结束 1 2 3 4
问题原因:forEach
底层的实现
// 核心逻辑for (var i = 0; i < length; i++) { if (i in array) { var element = array[i]; callback(element, i, array); }}
可以看到,forEach 拿过来直接执行了,这就导致它无法保证异步任务的执行顺序。比如后面的任务用时短,那么就又可能抢在前面的任务之前执行。
解决方法:使用for of
async function test() { let arr = [4, 2, 1] for(const item of arr) { const res = await handle(item) console.log(res) } console.log('结束')}