定義和用法
forEach() 調用數組的每個元素,並將元素傳遞給回調函數。
注意: forEach() 對於空數組是不會執行回調函數的。
用法:
array.forEach(function(currentValue, index, arr), thisValue)
1==> currentValue 必需。當前元素
2==> index 可選。當前元素的索引值,是數字類型的
3==> arr 可選。當前元素所屬的數組對象
4==> 可選。傳遞給函數的值一般用 "this" 值。
如果這個參數為空, "undefined" 會傳遞給 "this" 值
forEach 的注意點
forEach() 本身是不支持的 continue 與 break 語句的。
我們可以通 return 語句實現 continue 關鍵字的效果:
運用的場景(計算數字之和)
1.計算數組所有元素相加的總和:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = 0;
arr.forEach((currentIndex, index, curArr) => {
sum += currentIndex
// sum=sum+currentIndex
})
console.log('之和是', sum);
運用的場景(給原始數組新增key值)
//給原始數組的每一項新增一個屬性值
let arr = [{
id: '001',
name: '張三1'
}, {
id: '002',
name: '張三2'
}, {
id: '003',
name: '張三2'
}];
//給原始數組的每一項新增一個屬性值
arr.forEach((item, index) => {
item['addAttrs'] = ''
})
console.log('arr', arr);
--使用for of來出處理--
for (let item of arr) {
item['index'] = ''
}
console.log('arr', arr);
forEach 跳出當前的循環 return
//內容為3,不遍歷該項
var arr = [1, 2, 3];
arr.forEach(function(item) {
if (item === 3) {
return;
}
console.log(item);
});
forEach結合try跳出整個循環
//找到id為002,然后終止整個循環,返回當前這一項的值。
//使用 try-catch完成的
代碼如下
let arr = [{
id: '001',
name: '張三1'
}, {
id: '002',
name: '張三2'
}, {
id: '003',
name: '張三2'
}];
// 使用forEach跳出整個循環,使用rty-catch
function useForeach(Arr) {
let obj = {}
try {
Arr.forEach(function(item) {
if (item.id == '002') {
// 找到目標項,賦值。然后拋出異常
obj = item
throw new Error('return false')
}
});
} catch (e) {
// 返回id===002的這一項的數據
return obj
}
}
console.log(useForeach(arr))
forEach 與for循環的區別 【面試題】
1==> for可以用continue跳過當前循環中的一個迭代,forEach 用continue會報錯。但是可以使用return來跳出當前的循環
2==> for可以使用break來跳出整個循環,forEach正常情況無法跳出整個循環。
如果面試官問:如果非要跳出forEach中的循環,可以拋出一個異常來處理