2018-12-27 14:10:05 +08:00
|
|
|
|
|
|
|
|
|
## for循环
|
|
|
|
|
|
|
|
|
|
### for循环的结构
|
|
|
|
|
|
|
|
|
|
for循环举例:
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
for (var i = 1; i <= 100; i++) {
|
|
|
|
|
console.log(i);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
上方代码的解释:
|
|
|
|
|
|
|
|
|
|
![](http://img.smyhvae.com/20180117_2248.png)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
### for循环遍历
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
for (var i = 1; i < 13; i = i + 4) {
|
|
|
|
|
console.log(i);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
上方代码的遍历步骤:
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
程序一运行,将执行var i = 1;这条语句, 所以i的值是1。
|
|
|
|
|
然后程序会验证一下i < 13是否满足,1<13是真,所以执行一次循环体(就是大括号里面的语句)。
|
|
|
|
|
执行完循环体之后,会执行i=i+4这条语句,所以i的值,是5。
|
|
|
|
|
|
|
|
|
|
程序会会验证一下i < 13是否满足,5<13是真,所以执行一次循环体(就是大括号里面的语句)。
|
|
|
|
|
执行完循环体之后,会执行i=i+4这条语句,所以i的值,是9。
|
|
|
|
|
|
|
|
|
|
程序会会验证一下i < 13是否满足,9<13是真,所以执行一次循环体(就是大括号里面的语句)。
|
|
|
|
|
执行完循环体之后,会执行i=i+4这条语句,所以i的值,是13。
|
|
|
|
|
|
|
|
|
|
程序会会验证一下i < 13是否满足,13<13是假,所以不执行循环体了,将退出循环。
|
|
|
|
|
|
|
|
|
|
最终输出输出结果为:1、5、9
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
接下来做几个题目。
|
|
|
|
|
|
|
|
|
|
题目1:
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
for (var i = 1; i < 10; i = i + 3) {
|
|
|
|
|
i = i + 1;
|
|
|
|
|
console.log(i);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
输出结果:2、6、10
|
|
|
|
|
|
|
|
|
|
题目2:
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
for (var i = 1; i <= 10; i++) {
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
console.log(i);
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
输出结果:11
|
|
|
|
|
|
|
|
|
|
题目3:
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
for(var i = 1; i < 7; i = i + 3){
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
console.log(i);
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
输出结果:7
|
|
|
|
|
|
|
|
|
|
题目4:
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
for (var i = 1; i > 0; i++) {
|
|
|
|
|
console.log(i);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
死循环。
|