JavaScript Advanced Programming Reading Sharing Chapter 3 - 3.6 Statements

JavaScript Advanced Programming (4th Edition) Reading Sharing Note Recording

Applicable to comrades who are just getting started

 if statement

example:

if (i > 25) { 
 console.log("Greater than 25."); 
} else if (i < 0) { 
 console.log("Less than 0."); 
} else { 
 console.log("Between 0 and 25, inclusive."); 
}

do-while statement

The do-while statement is a post-test loop statement, that is, the exit condition is not evaluated until the code in the loop body is executed. In other words
In other words, the code in the loop body is executed at least once. The syntax of do-while is as follows:
do { 
 statement 
} while (expression);

case:

let i = 0; 
do { 
 i += 2; 
} while (i < 10); 
//在这个例子中,只要 i 小于 10,循环就会重复执行。i 从 0 开始,每次循环递增 2。
Note that post-test loops are often used in situations where the code inside the loop must be executed at least once before exiting.

 while statement

The while statement is a test loop statement, that is, the exit condition is detected first, and then the code in the loop body is executed.
grammar:
while(expression) statement

case:

let i = 0; 
while (i < 10) { 
 i += 2; 
}

for statement

The for statement is also to test the statement first, but it adds the initialization code before entering the loop, and the table to be executed after the loop is executed.
expression
grammar:
for (initialization; expression; post-loop-expression) statement

case:

let count = 10; 
for (let i = 0; i < count; i++) { 
 console.log(i); 
}

Equivalent to while loop:

let count = 10; 
let i = 0; 
while (i < count) { 
 console.log(i); 
 i++; 
}

for-in statement

Iterates the attribute key, not the value

grammar:

for (property in expression) statement

case:

var arr = [1,2,3]
    
for (let index in arr) {
  
  console.log(index)//0 1 2 string类型
}

for-of statement

grammar:

for (property of expression) statement

case:

var arr = [1,2,3]
    
for (let value of arr) {
  console.log(value) //1 2 3
}

 for in traverses the index of the array (that is, the key name), while for of traverses the array element value

break and continue statements 

The break statement is used to exit the loop immediately, forcing the execution of the next statement after the loop.
The continue statement is also used to exit the loop immediately, but execution starts again from the top of the loop.
break:
let num = 0; 
for (let i = 1; i < 10; i++) { 
 if (i % 5 == 0) { 
     break;
    }
    num++
}
console.log(num); // 4

continue:

let num = 0; 
for (let i = 1; i < 10; i++) { 
 if (i % 5 == 0) { 
 continue; 
 } 
 num++; 
} 
console.log(num); // 8

switch statement

grammar:

switch (expression) { 
 case value1: 
 statement
 break; 
 case value2: 
 statement 
 break; 
 case value3: 
 statement 
 break; 
 case value4: 
 statement 
 break; 
 default: 
 statement 
}

Guess you like

Origin blog.csdn.net/weixin_42307283/article/details/129028611