forEach

遍歷數(shù)組

let arr = [1, 2, 3, 4]
/**
  * forEach() 方法對(duì)數(shù)組的每個(gè)元素執(zhí)行一次提供的函數(shù)。
  * params: callback
  * params: thisArg 當(dāng)執(zhí)行回調(diào)函數(shù)時(shí)用作 this 的值(參考對(duì)象)。
  * return undefined forEach總是返回undefined且不可鏈?zhǔn)秸{(diào)用,一般放鏈?zhǔn)阶詈蟆?  */
arr.forEach(callback, this) // forEach()為數(shù)組中的每一個(gè)元素執(zhí)行一次callback
/**
  * callback為數(shù)組中每個(gè)元素執(zhí)行的函數(shù),該函數(shù)接收三個(gè)參數(shù):
  * params: currentValue 數(shù)組中正在處理的當(dāng)前元素。
  * params: index(可選) 數(shù)組中正在處理的當(dāng)前元素的索引。
  * params: array(可選) forEach() 方法正在操作的數(shù)組。
  */
function callback(currentValue, index, array) {  
  console.log(currentValue)  // 1 2 3 4
  console.log(index) // 0 1 2 3
  console.log(array) // [1,2,3,4] [1,2,3,4] [1,2,3,4] [1,2,3,4]
}

// 注意索引 3 被跳過(guò)了,因?yàn)樵跀?shù)組的這個(gè)位置沒(méi)有項(xiàng)
[1, 2, 3, , 4].forEach(callback)
// currentValue 1 2 3 4
// index 0 1 2 4
// array [1, 2, 3, empty, 4]

如果數(shù)組在迭代時(shí)被修改了

forEach 遍歷的范圍在第一次調(diào)用 callback 前就會(huì)確定。
調(diào)用 forEach 后添加到數(shù)組中的項(xiàng)不會(huì)被 callback 訪問(wèn)到。

// forEach 遍歷的范圍在第一次調(diào)用 callback 前就會(huì)確定。
// 調(diào)用 forEach 后添加到數(shù)組中的項(xiàng)不會(huì)被 callback 訪問(wèn)到。
arr.forEach(function(currentValue) {
  if(currentValue === 2) {
    arr.push(5)
  }
  console.log(currentValue) // 1 2 3 4
})
console.log(arr) // [1,2,3,4,5]

arr2在遍歷到b時(shí),刪除了第一項(xiàng),導(dǎo)致剩下的項(xiàng)移一個(gè)位置
forEach()不會(huì)在迭代之前創(chuàng)建數(shù)組的副本。


// arr在遍歷到b時(shí),刪除了第一項(xiàng),導(dǎo)致剩下的項(xiàng)移一個(gè)位置
// forEach()不會(huì)在迭代之前創(chuàng)建數(shù)組的副本。
let arr2 = ['a', 'b', 'c', 'd']
arr2.forEach(function(currentValue) {
  if(currentValue === 'b') {
    arr2.shift()
  }
  console.log(currentValue) // a b d
})
console.log(arr2) // b c d

使用thisArg

forEach若不傳this,callback里的this在非嚴(yán)格模式指向window,嚴(yán)格模式為undefined

function Counter() {
    this.sum = 0;
    this.count = 0;
}

Counter.prototype.add = function(array) {
    array.forEach(function(entry) {
        this.sum += entry;
        ++this.count;
    }, this); // 若不傳this,forEach里的this在非嚴(yán)格模式指向window,嚴(yán)格模式為undefined
    console.log(this === obj); // true
};

var obj = new Counter();
obj.add([1, 3, 5, 7]);

obj.count; 
// 4 === (1+1+1+1)
obj.sum;
// 16 === (1+3+5+7)

注意:沒(méi)有辦法中止或者跳出 forEach() 循環(huán)

若你需要提前終止循環(huán),你可以使用:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容