---
# System prepended metadata

title: "\U0001F4DA forEach"
tags: [javascript]

---

📚 forEach
===
JS:
```javascript=
//forEach 基本寫法 
let data = [10,20,30]; 
data.forEach(function(value,index,array){console.log(value,index,array);}); 
// 10 0 [10,20,30] 
// 20 1 [10,20,30] 
// 30 2 [10,20,30] 
// index與array是可以被省略的 

//另外有2種寫法 
data.forEach(value=>console.log(value)); 

function printData(value,index,array){console.log(value,index,array);} 
data.forEach(printData); 

//讀取陣列裡的物件 
let data = [ 
{ name:"Tom", 
	sex:"male"}, 
{ name:"Mary", 
	sex:"female"}]; 

data.forEach(function(value){console.log(value.name,value.sex);}); 
// Tom male 
// Mary female 

//加總陣列裡的男女生人數(善用物件取代變數的寫法) 
let data = [ 
{ name:"Tom", 
	sex:"male"}, 
{ name:"Mary", 
	sex:"female"}, 
{ name:"Christy", 
	sex:"female"}, 
{ name:"Eva", 
	sex:"female"}]; 

let people = { 
	male:0, 
	female:0} 

data.forEach(function(value){ 
	if(value.sex === "female"){ 
		people.female++; 
	}else{ 
		people.male++; 
	} 
}); 

console.log(people); 

//整理外接的資料成自己要的陣列 

let data = [ 
{ charge:"免費", 
	name:"A充電站"}, 
{ charge:"投幣", 
	name:"B充電站"}, 
{ charge:"免費", 
	name:"C充電站"}, 
{ charge:"投幣", 
	name:"D充電站"}, 
{ charge:"投幣", 
	name:"E充電站"},] 

let total ={ 
	free:[], 
	charge:[]} 

data.forEach(function(value){ 
	if(value.charge==="免費"){ 
		total.free.push(value); 
	}else if(value.charge==="投幣"){ 
		total.charge.push(value); 
	}}); 

console.log(`目前免費充電站有${total.free.length}處`);//目前免費充電站有2處 
console.log(`目前投幣充電站有${total.charge.length}處`);//目前投幣充電站有3處
```
:::success
用filter改寫會變成 total.charge = data.filter(item=>item.charge==="投幣");
:::
:::success
除了 forEach 以外的其他陣列操作(map、filter)都會回傳陣列或一個值(return)，在forEach等號的左方如果放置一個變數，那麼此變數會是 undefined (沒有回傳任何值)。
:::
JS:
```javascript=
let people = [ 
{ 
	name: '小明', 
	money: 500 
}, 
{ 
	name: '漂亮阿姨', 
	money: 3000 
}, 
{ 
	name: '杰倫', 
	money: 60000 
}, 
{ 
	name: '老媽', 
	money: Infinity 
} 
]; 

const forEachLoop = people.forEach(function(item, index, array){ 
	console.log(item, index, array); // 物件, 索引, 全部陣列) 
}); 

console.log(forEachLoop); // undefined
```