---
title: forEach
tags: forEach,
description:
---
forEach
===
**forEach**會把**陣列**資料==一筆一筆取出==,代入參數後去做處理運算。
- 代入參數順序分別是```item```、```index```、```array```,名稱可自行定義。
```javascript=
let data = [1, 2, 3,];
data.forEach(function(item, index, array){
console.log(item, index, array);
})
// 1 0 (3) [1, 2, 3]
// 2 1 (3) [1, 2, 3]
// 3 2 (3) [1, 2, 3]
```
- 箭頭函式寫法
```javascript=
let data = [1, 2, 3,];
data.forEach((item, index, array) => {
console.log(item, index, array);
});
```
:::info
**這邊需要特別提醒,在 `forEach()` 函式內用 return 是無效的。除非程式碼有誤,否則並沒有中止 `forEach()` 的辦法**
:::
```javascript=
let data = ["a", "b", "c"];
data.forEach(function(item, index, array){
console.log(item, index, array);
// 程式碼會忽略這個 return
return
})
```
<br>
### 陣列數字累加、forEach參數作用域
- 每次進行forEach取出陣列``data``的item做累加
- 每次進行forEach完成,會把**大括號**的資料清除,所以用來累加的``total``不會放在大括號內。(forEach大括號內找不到total,會==向外層尋找==)
-
```javascript=
let data = [10, 20, 30,];
let total = 0;
data.forEach(function(item, index) {
total += item;
});
console.log(total); // 60
```
<br>
### 搭配if,篩選陣列有幾個偶數
- 把陣列``data``內的偶數取出,加入到陣列``evenArray``內,並檢查共幾個偶數。
```javascript=
let data = [7, 22, 39, 46, 56, 62, 73];
let evenArray = []; //賦予空陣列
// 把陣列的值一一取出判斷是否為偶數,為偶數就push到陣列evenArray內
data.forEach(function(item, index) {
item % 2 ? '' : evenArray.push(item);
});
console.log(evenArray.length);
```
<br>
### forEach讀取資料
- 把陣列``data``內的物件資料一一取出,把姓名、性別資料呈現出來
```javascript=
let data = [
{
name: 'tom',
sex: 'male',
},
{
name: 'mary',
sex: 'female',
}
];
data.forEach(function(item, index) {
console.log(`${item.name}的性別是${item.sex}`);
});
// tom的性別是male
// mary的性別是female
```
<br>
### 男女生人數計算
把變數``data``的資料用``forEach``分析
- 用一個物件存放下列取得的資料
- 計算男生/女生人數分別是多少人?
- 把男生/女生的姓名分別存放在兩個陣列內。
```javascript=
let data = [
{
name: 'tom',
sex: 'male',
},
{
name: 'mary',
sex: 'female',
},
{
name: 'judy',
sex: 'female',
},
{
name: 'jane',
sex: 'female',
},
{
name: 'john',
sex: 'male',
}
];
let people = {
male: 0,
female: 0,
maleNameList: [],
femaleNameList: [],
};
data.forEach(function(item, index) {
if (item.sex === 'male') {
people.male += 1;
people.maleNameList.push(item.name);
} else if (item.sex === 'female') {
people.female += 1;
people.femaleNameList.push(item.name);
}
});
console.log(people);
```

<br>