作用:
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)
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。