forEach會將陣列元素逐一取出,傳給使用者定義函數callback,在callback函數需接收陣列的相關資訊,這些資訓有下列參數可以使用:
index與 array都是選用,你可以單純使用currentValue不加上其他。
例 ❶
let data = [30];
data.forEach(function(item,index,array){
console.log(item,index,array);
})
例 ❷
陣列資料
let data = [
{
name:"tom" ,
sex:"male"
},
{
name:"mary",
sex:"female"
},
{
name:"denny" ,
sex:"male"
},
{
name:"cindy",
sex:"female"
},
{
name:"tommy" ,
sex:"male"
},
{
name:"lisa",
sex:"female"
}
];
處理
let people = {
male:0,
female:0
}
data.forEach(function(item,index){
if(item.sex == "male"){
people.male += 1;
}else if(item.sex == "female"){
people.female += 1;
}
})
console.log("男生" + people.male + "人");
console.log("女生" + people.female + "人");
(圖片來源:六角學院)