forEach
forEach() 方法按升序为数组中含有效值的每一项执行一次 callback 函数,那些已删除或者未初始化的项将被跳过(例如在稀疏数组上)。
参数:
1.可依次向 callback 函数传入三个参数:
- 数组当前项的值
- 数组当前项的索引
- 数组对象本身
2.如果 thisArg 参数有值,则每次 callback 函数被调用时,this 都会指向 thisArg 参数。如果省略了 thisArg 参数,或者其值为 null 或 undefined,this 则指向全局对象。按照函数观察到 this 的常用规则,callback 函数最终可观察到 this 值。
注意事项:
- 1.forEach() 遍历的范围在第一次调用 callback 前就会确定。调用 forEach 后添加到数组中的项不会被 callback 访问到。
var arr = [1, 2, 3, 4, 5];
let count = 0
arr.forEach(function (item,index,arr) {
count++
if (item === 2) {
arr.push(8)
}
console.log(item);
})
console.log('count的值' + count)
console.log(arr)
- 2.如果已经存在的值被改变,则传递给 call