1. forEach遍历数组时会直接跳过空值,for-of空值则不会
let array = ['a', , 'c'];
// a c
array.forEach(element => {
console.log(element) // 跳过空值
})
// a undefined c
for (const item of array) {
console.log(item) // 没有跳过空值
}
2. forEach遍历数组时,传入的函数建议使用箭头函数
array.forEach(function (item) {
console.log(this) // 全局对象
})
array.forEach(item => {
console.log(this) // {}
})
3. forEach遍历数组,执行异步操作时,执行顺序是并行的,不建议使用;for-of遍历数组,执行异步操作时,执行顺序则为串行的,建议使用。如果要并行操作时,建议使用Promise.all实现。