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值。