文章目录
forEach 方法对数组中的每个元素执行一次给定的函数
语法:arr.forEach(callback(currentEle[, index[, array]])[, thisArg])
callback:为数组中每个元素执行的回调函数,该函数接收一到三个参数
currentEle:数组正在处理的当前元素
index:(可选)数组正在处理的当前元素的下标
array:(可选)方法正在操作的数组本身
thisArg:(可选)当执行回调函数时,用作this的值。如果thisArg参数有值,则每次callback函数调用时,this都会指向thisArg。如果省略了thisArg,或者其值为null或undefined,thisArg参数都会指向全局对象。
返回值:undefined
// forEach 不对未初始化的值进行操作
const arr = ['a', , 'b']
arr.forEach(function(item, index) {
console.log('index: '+ index + ' item: '+ item)
// index: 0 item: a
// index: 2 item: b
})
// 注意索引 1 被跳过了,因为在数组的这个位置没有项
// 如果数组在迭代时被修改了,则其他元素会被跳过
const arr = ['a', 'b', 'c', 'd']
arr.forEach(function(item, index) {
if(item === 'b') {
arr.shift()
}
console.log('index: '+ index + ' item: '+ item)
})
// index: 0 item: a
// index: 1 item: b
// index: 2 item: d
除了抛出异常外,没有办法跳出或者终止forEach 循环。如果需要跳出循环,forEach 不是首选的。
forEach 不会直接改变调用它的数组,但是那个数组可能会被callback函数改变。
forEach 为数组中每个元素执行一次callback 函数。总是返回undefined 值并且不能链式调用。