while循环

1
2
3
4
5
6
var num = 0;
while (num < 2) {
num += Math.random();
}

console.log('at last,num is:',num);

do while循环

1
2
3
4
5
6
7
var num = 0;
do {
num += Math.random();

} while(num < 2);

console.log('at last,num is:',num);

do while先执行do语句块再判断,所以至少先执行一遍再判断是否继续循环

for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
for (var i = 1;i < 5;i++) {
console.log(i)
}
//第二种写法
var sum = 0;
var j = 0;
for (; j < 10;) {
sum += j;
j++;
}
console.log(sum)
//遍历对象
var o = {
a : 1,
b : 2,
c :'str',
d : false
};
for (var key in o) {
console.log('key:',key,'value:',o[key])
}

switch语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var s = 'str';
switch(s) {
case 'str':
console.log('is str');
break;
case false:
console.log('is boolean false');
break;
default:
console.log('default statment');
break;
}
//逐一寻找case中的表达式,满足则打印case下的语句,如果都不符合就会执行default语句
//多个case语句满足时,只会执行第一个

break循环

1
2
3
4
5
6
for (var i = 0; i < 10;i++) {
if (i === 5) {
break;
}
console.log('i:',i);
}

continue跳出本次循环

1
2
3
4
5
6
for (var i = 0; i < 10;i++) {
if (i === 5) {
continue;
}
console.log('i:',i)
}