关于es6:forEach和for循环方法

5次阅读

共计 740 个字符,预计需要花费 2 分钟才能阅读完成。

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)
}
正文完
 0