---
# System prepended metadata

title: forEach&for...in&for...of迴圈
tags: [ALPHACampWeek3]

---

###### tags:`ALPHACampWeek3`

forEach&for...in&for...of迴圈
===
![](https://i.imgur.com/bmexYhj.png)

# 第一種 一般的for迴圈
for (let i = 0; i < words.length; i++) {
  console.log(words[i])
}

# 第二種 把函式根forEach寫在一起
words.forEach(function print(word) {
  console.log(word)
})

# 第三種 forEach跟函式分開寫

const print = function (word) {
  console.log(word)
}

words.forEach(print)

# 第四種 箭頭函示法
words.forEach( word => console.log(word) )

實際使用
---
- forEach沒有回傳值

```javascript=
const scores = [1, 2, 3]
let sum = 0
scores.forEach(function (score, index) {
  console.log(`現在輸到第 ${index} 項，值是 ${score}`)
  sum += score
  console.log(`現在總和是： ${sum}`)
})
```
![](https://i.imgur.com/7lGepbB.png)


# for...in

- 如果是物件 prop 就是key 
```javascript=
var john = {
  firstName: 'John',
  lastName: 'Doe'
};

for (var prop in john) {
  console.log(prop + ':' + john[prop]);
}

//firstName: 'John'
//lastName: 'Doe'
```

- 如果是陣列 prop 就是index
```javascript=
var arr = ['John', 'Jane', 'Jim']
for (var prop in arr) {
  console.log(prop + ': ' + arr[prop])
}
//0:John
//1:Jane
//2:Jim
```

## for...of迴圈
```jsx=
const movies = []
axios.get(INDEX_URL).then(response =>{
  for(const movie of response.data.results){
    movies.push(movie);
  }
})
```


