JS的语句(选择 循环)

36 阅读1分钟

5.条件语句

if ,if  else

 if( 1 > 2) {
 document.write('a');
 }

switch case

// 根据浏览器端输入的值的不同执行不同的操作
let n = parseInt(window.prompt('input'));
switch(n) {
    case 'a': 
        console.log('a');
        break;
    case 'b': 
        console.log('b');
        break;    
    case 'c'console.log('c');
}

条件语句中的continue 和 break

// continue (跳过本次循环)
for(var a = 0; a < 100; a++) {
    if(a % 7 === 0 || a % 10 === 7) {
        continue;
    }
    console.log(a);
}
// for循环中如果a逢7或是7的倍数那么跳出本次循环,输出其他的小于100的数字
 
// break (直接结束循环)
// 判断今天输入的date是星期几
let date = parseInt(window.prompt("input"));
switch(date) {
    case "monday": 
    case "tuesday": 
    case "wednesday": 
    case "thursday": 
    case "friday":
        console.log("工作日"); 
        break;
    case "monday": 
    case "sunday":
        console.log("休息日");
}
 
// 上述程序如果没有break,会一直走完case "sunday"

2.循环语句

①for循环

// 如何方便地打印10个a
for(var a = 0; a < 10; a++) {
    document.write(a)
}
 
// 以上的for循环还可以写成下面的
var a = 0;
for(;a < 10;) {
    document.write(a);
    a++;
}

②while循环

var a = 0;
while(a < 10) {
    document.write(a);
    a++;
}

do{} while() 循环

 do {
 document.write(a);
    a++;
 } while (a < 10);
 // do{} while() 循环,不管满足不满足条件,都会执行一次