if 语句
if....else 语句
if....else if....statement
嵌套 if 语句
switch 语句
if (condition) { // block of code will execute if the condition is true }
注意: if 语句必须以小写字母书写。使用大写字母(If 或 IF)会导致 JavaScript 错误。
var x = 78; if (x>70) { console.log("x is greater") }
x is greater
if (condition) { // block of code will execute if the condition is true } else { // block of code will execute if the condition is false }
var x = 40, y=20; if (x < y) { console.log("y is greater"); } else { console.log("x is greater"); }
x is greater
if (condition1) { // block of code will execute if condition1 is true } else if (condition2) { // block of code will execute if the condition1 is false and condition2 is true } else { // block of code will execute if the condition1 is false and condition2 is false }
var a = 10, b = 20, c = 30; if( a > b && a > c) { console.log("a is greater"); } else if( b > a && b > c ) { console.log("b is greater"); } else { console.log("c is greater"); }
c is greater
if (condition1) { Statement 1; //It will execute when condition1 is true if (condition2) { Statement 2; //It will execute when condition2 is true } else { Statement 3; //It will execute when condition2 is false } }
var num = 20; if (num > 10) { if (num%2==0) console.log( num+ " is greater than 10 and even number"); else console.log(num+ " is greater than 10 and odd number"); } else { console.log(num+" is smaller than 10"); } console.log("After nested if statement");
20 is greater than 10 and even number After nested if statement
一个 switch 表达式可以有一个或多个 case 值。
break 和 default 关键字的使用是可选的。
case 语句只能包含常量和文字。它不能是表达式或变量。
除非您在每个块的代码后放置一个中断,否则执行将不断流入下一个块。
没有必要最后将 default case 放在 switch 块中。
switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; }
var num = 5; switch(num) { case 0 : { console.log("Sunday"); break; } case 1 : { console.log("Monday"); break; } case 2 : { console.log("Tuesday"); break; } case 3 : { console.log("Wednesday"); break; } case 4 : { console.log("Thursday"); break; } case 5 : { console.log("Friday"); break; } case 6 : { console.log("Saturday"); break; } default: { console.log("Invalid choice"); break; } }
Friday