forEach 是陣列(Array)的一個方法,用來走訪陣列中的每一個元素,並對每個元素執行你指定的動作
基本語法
let data = [30,20,10];
data.forEach(function(item,index,array){
console.log(item,index,array);
})
//輸出
//30 0 (3) [30, 20, 10]
//20 1 (3) [30, 20, 10]
//10 2 (3) [30, 20, 10]
forEach的三個參數的"位置"含意
這三個可以隨意更改名稱
範例一-基本輸出
const drinks = ["奶茶", "紅茶", "綠茶"];
drinks.forEach(function(drink) {
console.log("我要一杯" + drink);
});
// 輸出:
// 我要一杯奶茶
// 我要一杯紅茶
// 我要一杯綠茶
範例二-設定特定格式抓取資料
let data = [
{ name: "Tom", sex: "male" },
{ name: "Mary", sex: "female" }
];
data.forEach(function(item){
console.log(item)
//輸出
//{name: 'Tom', sex: 'male'}
//{name: 'Mary', sex: 'female'}
console.log(item.name,item.sex)
//輸出
//Tom male
//Mary female
})
範例三-運用index領號碼牌
const drinks = ["奶茶", "紅茶", "綠茶"];
drinks.forEach(function(drink, index, array) {
console.log(index + 1 + "號:" + drink);
});
// 輸出:
// 1號:奶茶
// 2號:紅茶
// 3號:綠茶
情境一:印出購物清單
const shoppingList = ["雞蛋", "牛奶", "麵包"];
shoppingList.forEach(function(item) {
console.log("要買:" + item);
});
//輸出
//要買:雞蛋
//要買:牛奶
//要買:麵包
情境二:計算總價(搭配外部變數累加)
const prices = [30, 45, 60];
let total = 0; // 這段放外面才會記憶已累加數值
prices.forEach(function(price) {
total = total + price;
});
console.log("總金額:" + total);
//輸出 總金額:135
情境三:搭配陣列索引,做編號清單
const orders = ["珍珠奶茶", "四季春", "百香果茶"];
orders.forEach(function(order, index) {
console.log((index + 1) + ". " + order);
});
//輸出
//1. 珍珠奶茶
//2. 四季春
//3. 百香果茶
篩選偶數
let data = [30,40,100,3333,556951];
let total = 0;
let newData =[];
data.forEach(function(item,index){
if(item % 2 == 0){ //該元素整除後為零時
total += 1; //計算幾筆資料
newData.push(item); //將元素推送至空陣列
}
})
console.log( total);//輸出 3
console.log(newData);//輸出 (3) [30, 40, 100]
搭配 if 判斷式的範例
const prices = [30, 80, 45, 120];
prices.forEach(function(price) {
if (price > 50) {
console.log(price + " 元,有點貴喔");
} else {
console.log(price + " 元,可以接受");
}
});
//輸出
//30 元,可以接受
//80 元,有點貴喔
//45 元,可以接受
//120 元,有點貴喔
搭配 DOM 操作的範例
//HTML:<button class="button" type="submit">提交</button>
const buttons = document.querySelectorAll("button");
buttons.forEach(function(button) {
button.addEventListener("click", function() {
alert("按鈕被點擊了");
});
});
這是初學者最容易搞混的地方。forEach 執行完,回傳的是 undefined,它不會幫你產生一個新陣列
不管你在裡面寫什麼 return,forEach 執行完永遠回傳 undefined。這是語言規格定死的,沒有例外
const numbers = [1, 2, 3];
const result = numbers.forEach(function(num) {
return num * 2;
});
console.log(result); // undefined,不是 [2, 4, 6]!