for循环和forEach的区别

107 阅读1分钟

1. forEach不能遍历部分类数组对象

  • 因为forEach是数组原型上的方法,部分类数组对象上没有forEach方法
  • 解决方法:
    • 可以将类数组对象转为数组后再使用forEach方法
    • 使用for-of等方法进行遍历。因为类数组对象是有[Symbol.Iterator]方法的。详细可以参考juejin.cn/post/708589…
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<script>
  const domBox = document.getElementsByClassName('box')
  domBox.forEach(element => {
    console.log(element)
  }); // 报错

  // 解决方法1,使用querySelectorAll得到的类数组对象(不是数组),有forEach方法
  const domBox = document.querySelectorAll('.box')
  domBox.forEach(element => {
    console.log(element)
  });
  // 解决方法2,类数组对象是有[Symbol.Iterator]方法,因此可以使用for-of遍历      for (const iterator of domBox) {
  const domBox = document.getElementsByClassName('box')
  for (const iterator of domBox) {
    console.log(iterator)
  }
</script>

2. 中断循环方式不同

  • for循环通过continue中断一次循环,break中断后续循环,不能使用return中断(会报错)
  • forEach是函数,不能使用continue和break中断循环,可以使用return中断一次循环,throw中断后续循环
let a = [1, 2, 3, 4]
for (var i = 0; i < a.length; i++) {
  if (i === 2) {
    // break // 打印结果:1
    continue // 打印结果:124
  }
  console.log(a[i])
}
try {
  // 需要使用trycatch包裹,避免影响其他代码执行
  a.forEach(element => {
    if (element === 2) {
      // return  // 中断一次循环,打印结果:124
      throw new Error('中断循环')  // 中断后续循环,打印结果:1
    }
    console.log(element)
  })
} catch (error) {}

3. forEach执行时,数组长度会锁定,更改后不影响后续操作

let a = [1, 2, 3, 4]

// for循环
// let a = [1, 2, 3, 4]
// for (var i = 0; i < a.length; i++) {
//   if (i === 2) {   // 需要加条件限制,否则会死循环
//     a.push(5)
//   }
//   console.log(a[i]) // 12345
// }

// forEach
a.forEach((element, index, arr) => {
  if (index === 2) {  
    arr.push(5)
  }
  console.log(element)  // 1234
})
console.log(a)  //12345

// forEach index无法修改
a.forEach((element, index, arr) => {
  console.log(index) // 01234
  index++
})

4. forEach没有返回值,就算使用的return,也没有返回值

  • 由于forEach方法接收的是一个回调函数,在回调函数中使用return,并不会影响forEach方法的返回值
let a = [1, 2, 3, 4]
const res = a.forEach((element, index, arr) => {
  return 111
})
console.log(res) // undefined

5. for循环性能上比forEach更快

  • 性能比较:for > forEach > map