---
# System prepended metadata

title: JavaScript (loop)
tags: [Javascript]

---

# JavaScript (loop)
###### tags: `Javascript`
## for loop
for 迴圈會遵照指定的次數, repeating the command in side (...), the repeating count is decided by the back of [for] ()



```javascript=
for(初始值；迴圈條件；每次執行後的動作){
console.log(變數)
}
```

```javascript=
for(var i =1; i<=10; i=i+1){
				console.log(i)
			}
```

## while loop
當while迴圈()內的條建true 便會執行{...}

```javascript=
while(條件式){
此處重覆執行
}
```

1. monster has 100 health it must be decreased to 0
2. every round you can decrease the monster's health by 30, the attack damage is randomly chosen
3. every round 's attack damage equal to the amount of hear that the monster loss
4. Before the heart decrease under 0 repeat number 2 and number 4 step

change the following rules to Javascript

**Practice**
Put the monster's heath in to "enemy", and every damage set to "attack"

**Coding Practice**
put loop and battle's output the message

```javascript=
var enemy = 100;
			var attack;
			count = 0;
			window.alert('battle started');
			
			while(enemy >0){
				attack = Math.floor(Math.random()*31);
				console.log("Monster's damage "+attack+" damage");
				enemy = enemy - attack;
				
				count++; //count = count + 1;
			
			}
			
			console.log('in round '+ count + ' the monster has fallen')
```

## for loop and while's difference
if it knows the the loop times at start