2. 丶亳从仍 dowhile
do {
// 仍仂 亳从仍舒
} while (仄仂于舒)
亳从仍舒亟:
var i = 0;
do {
alert( i );
i++;
} while (i < 3);
3. 丶亳从仍 for
for (仗仂舒仂从; 仄仂于舒; 从仂从) {
// ... 仍仂 亳从仍舒 ...
}
亳从仍舒亟:
var i;
for (i = 0; i < 5; i++) {
alert( i );
}
弍仂
for (var i = 0; i < 5; i++) {
alert(i); // 0, 1, 2, 3, 4
}
4. 亠亠亳于舒仆仆 亳从仍
亳亠从亳于舒 break.
弌仄舒 亳亠仍, 仗仂从亳 从仂亳于舒 于于仂亟亳
var sum = 0;
while (true) {
var value = +prompt("于亠亟 亳仍仂", '');
if (!value) break; // (*)
sum += value;
}
alert( '弌仄舒: ' + sum );
11. 仂亰于磶从亳
for (var i=2; i<=10; i += 2) {
alert( i );
}
弍仂
for (var i = 2; i <= 10; i++) {
if (i % 2 == 0) {
alert( i );
}
}
弍仂
var i = 2;
while (i<=10) {
alert ( i );
i += 2;
}
13. 仂亰于磶从亳
var num =1;
while (num <100 && !!num ==true){
num = prompt ("于亠亟 亳仍仂 > 100", '');
}
弍仂
var num;
do {
num = prompt("于亠亟 亳仍仂 > 100", 0);
} while (num <= 100 && num != null);
14. 仂仆从 switch
弌亳仆舒从亳:
switch(x) {
case 'value1': // if (x === 'value1')
...
[break]
case 'value2': // if (x === 'value2')
...
[break]
default:
...
[break]
}
15. 亳从仍舒亟:
var a = '于亠仆舒';
switch (a) {
case '亰亳仄舒':
alert( '仂仍仂亟仆仂' );
break;
case '于亠仆舒':
alert( '亠仗仍仂' );
break;
case '仍仂':
alert( '仗亠从仂仆仂' );
break;
default:
alert( '仄仂从仂' );
}
16. 亊从仂 break 仆亠仄舒, 仂 于亳从仂仆舒仆仆 仗亟亠 仆亳亢亠 仗仂
仆舒仗仆亳 case, 仗亳 仂仄 仆 仗亠亠于从亳
亞仆仂ム.
var a = '于亠仆舒';
switch (a) {
case '亰亳仄舒':
alert( '仂仍仂亟仆仂' );
case '于亠仆舒':
alert( '亠仗仍仂' );
case '仍仂':
alert( '仗亠从仂仆仂' );
default:
alert( '仄仂从仂' );
}
亳于亠亟亠 仗仂 亠亰 亠仗仍仂, 仗亠从仂仆仂, 仄仂从仂.
17. 仗于舒仆仆 case
仍从舒 亰仆舒亠仆 case 仄仂亢仆舒 亰亞仗于舒亳.
switch (new Date().getDay()) {
case 4:
case 5:
text = "弌从仂仂 于亳亟仆";
break;
case 0:
case 6:
text = "弌仂亞仂亟仆 于亳亟仆亳亶";
break;
default:
text = "亳亟仆 从仂仍亳 弍亟";
}
alert(text);
个舒亞仄亠仆 new Date().getDay() 仂亰亞仍礌亠仄仂 仗亰仆亠. 仆
于亳于仂亟亳 仆仂仄亠 亟仆 亳亢仆, 仗亳仂仄 仆亠亟仍 0, 仗仂仆亠亟仍仂从
1
18. 舒亟舒舒 21
亠亠仗亳 从仂亟 亰 if switch.
var a = +prompt('a?', '');
if (a == 0) {
alert( 0 );
}
if (a == 1) {
alert( 1 );
}
if (a == 2 || a == 3) {
alert( '2,3' );
}
19. 仂亰于磶仂从
var a = +prompt('a?', '');
switch (a) {
case 0:
alert( 0 );
break;
case 1:
alert( 1 );
break;
case 2:
case 3:
alert( '2,3' );
break;
}