关于es6:forEach和for循环方法

forEach()办法用于调用数组的每一个元素,并将元素传递给回调函数

语法:

array.forEach(function(currentValue, index, arr), thisValue)

  • currentValue:必填,以后元素。
  • index:可选,以后元素的索引。
  • arr:可选,以后元素所属的数组对象。
  • thisValue:可选,传递给函数的值个别用this值,如果这个参数为空,”undefined”会传递给”this”值。(这个参数个别很少填)

留神:currentValue 必须放在index的后面

const list = ['a', 'b', 'c', 'd']
list.forEach((item, index, arr) => {
  console.log(item, index, arr)
})

//for循环与以上成果等同

for (let i = 0; i < list1.length; i++) {
  const element = list[i];
  console.log(element, i, list)
}

迭代

1、 forEach() 对于空数组是不会执行回调函数的。
2、 for能够用continue跳过循环中的一个迭代,forEach用continue会报错。
3、 forEach() 须要用 return 跳过循环中的一个迭代,跳过之后会执行下一个迭代。

const list = ['a', 'b', 'c', 'd']
  list3.forEach((item, index) => {
    if (index == 2) {
      return;//跳出迭代
    }
   console.log(item, index)
});

for (let i = 0; i < list.length; i++) {
  if (i == 2) {
    continue;//跳出迭代
  }
  console.log(list[i], i)
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理