if
Conditional statement: You can judge a statement before it is executed. If the condition is true, the statement is executed. If the condition is not true, the statement is not executed
Chestnut 🌰
var score = prompt("Please enter your final grade (0-100)")
if(score > 100 || score < 0 || isNaN(score)){
alert("Invalid input");
}else{
if(score == 100){
alert("Three Days at Disney");
}else if(score >= 80){
alert("Make a hand.");
}else if(score >= 60){
alert("Test volume");
}else{
alert("A stick"); }}// As long as there is one statement executed, there is no further execution
Copy the code
switch
Also called conditional branch statements
switch(true) {case score >= 60:
console.log("Qualified");
break;
default:
console.log("Unqualified");
break;
}
Copy the code
- Will be executed once
case
The value of the following expressionswitch
The value of the final conditional expression is compared. - If the comparison value is true, the subsequent code is executed and can be used
break
Used to quitswitch
statements - If all comparisons result in false, only execute
default
while
cycle
Judge before you execute
- Evaluate the expression first
- If the value is true, the body of the loop is executed
- After the body of the loop completes, we continue to evaluate the expression
- If the value is true, the body of the loop continues
- Until the value is false, the loop is terminated
Chestnut 🌰
while (true) {
var score = prompt("Please enter your final grade (0-100)");
if (score >= 0 && score <= 100) {
break;
}
alert("Please enter a valid score!!");
}
if (score == 100) {
alert("Three Days at Disney");
} else if (score >= 80) {
alert("Make a hand.");
} else if (score >= 60) {
alert("Test volume");
} else {
alert("A stick");
}
Copy the code
for
while (true) {
forInitialize the expression; Conditional expression; Update expression){statement ···}for(var i = 0; i < 10; i++){
alert(i);
}
Copy the code
- Execute the initialization expression to initialize the variable
- Execute the conditional expression to determine whether to execute the loop
- Execute the update expression and continue to execute the conditional expression after the update expression is executed
Chestnut 🌰
var num = prompt("Please enter an integer greater than 1:");
if (num <= 1) {
alert("This value is not valid");
} else {
var flag = true;
for (var i = 2; i < num; i++) {
if (num % i == 0) {
If num is divisible by I, then the value of num is not prime. If num=11, then I is a direct number from 2 to 10.
flag = false; }}// The for loop fetches all numbers where num divisible into I
if (flag) {
alert(num + "Prime number!!");
} else {
alert(num + "Not prime."); }}Copy the code
nestedfor
cycle
The inner for loop executes before the outer for loop executes
// Scenario: Print a prime number between 2 and 100
for (var i = 2; i <= 100; i++) {
var flag = true;
for (var j = 2; j < i; j++) {
if (i % j == 0) {
flag = false; }}if (flag) {
console.log(i); }}Copy the code