forEach()
方法对数组的每个元素执行一次提供的函数。
let a = ['a', 'b', 'c']; a.forEach(function(element) { console.log(element); }); // a // b // c
语法:
array.forEach(callback(currentValue, index, array){ //do something }, this) array.forEach(callback[, thisArg])
参数:
callback
为数组中每个元素执行的函数,该函数接收三个参数:
- currentValue(当前值)
- 数组中正在处理的当前元素。
- index(索引)
- 数组中正在处理的当前元素的索引。
- array
- forEach()方法正在操作的数组。
thisArg
可选可选参数。当执行回调 函数时用作
this的
值(参考对象)。
描述:
forEach
方法按升序为数组中含有效值的每一项执行一次callback
函数,那些已删除(使用delete
方法等情况)或者未初始化的项将被跳过(但不包括那些值为 undefined 的项)(例如在稀疏数组上)。
callback
函数会被依次传入三个参数:
- 数组当前项的值
- 数组当前项的索引
- 数组对象本身
如果给forEach传递了thisArg
参数,当调用时,它将被传给callback
函数,作为它的this值。否则,将会传入 undefined
作为它的this值。callback函数最终可观察到this值,这取决于 函数观察到this
的常用规则。
forEach
遍历的范围在第一次调用 callback
前就会确定。调用forEach
后添加到数组中的项不会被 callback
访问到。如果已经存在的值被改变,则传递给 callback
的值是 forEach
遍历到他们那一刻的值。已删除的项不会被遍历到。如果已访问的元素在迭代时被删除了(例如使用 shift()
) ,之后的元素将被跳过 - 参见下面的示例。
例子:
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } // 注意索引2被跳过了,因为在数组的这个位置没有项 [2, 5, ,9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[3] = 9 [2, 5,"" ,9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = // a[3] = 9 [2, 5, undefined ,9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = undefined // a[3] = 9 let xxx; // undefined [2, 5, xxx ,9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = undefined // a[3] = 9
//从每个数组中的元素值中更新一个对象的属性:
function Counter() { this.sum = 0; this.count = 0; } Counter.prototype.add = function(array) { array.forEach(function(entry) { this.sum += entry; ++this.count; }, this); //console.log(this); }; var obj = new Counter(); obj.add([1, 3, 5, 7]); obj.count; // 4 === (1+1+1+1) obj.sum; // 16 === (1+3+5+7)
因为
thisArg
参数 (this
) 传给了forEach(),每次调用时,它都被传给
callback函数,作为它的t
his值。