Conditional statement, Loop statement
First, if
1. If
Grammar:
if (condition) { true when executing code }
2. If Else
Grammar:
if (condition) { true when executing code }Else { true Code to execute at time }
3. If ElseIf else
Grammar:
if (Condition 1) { true when executing code }Elseif (condition 2) { True code executed at the time of the code}else { true }
Ps:else if can be used more than once, the last else statement can no longer judge the condition.
Second, switch
Grammar:
Switch (n) { case 1: 1 break ; Case 2: 2 break ; default : Case code executed at different time in case 2}
How it works: first set an expression n (usually a variable). The value of the subsequent expression is compared to the value of each case in the structure. If there is a match, the code block associated with the case is executed. Use break to prevent your code from automatically running down a case.
Default keyword: At the end, when all previous conditions (case) do not match, the statement after the default is executed
var day=New Date (). GetDay (); Switch (day) { case 6: x= "Today it ' s Saturday"; Break ; case 0: x= "Today it ' s Sunday"; Break ; default : x= "Looking forward to the Weekend";}
Third, for
Grammar:
for (statement 1; Statement 2; Statement 3) { the code block being executed }
Statement 1 executes before the Loop (code block) starts
Statement 2 defining conditions for running loops (code blocks)
Statement 3 executes after a loop (code block) has been executed
PS: The statement of the all-in-one can be omitted
Syntax when omitted:
// Omit statement 1: var i=2,len=cars.length; for (; i<len; i+++ "<br>");}
// Omit Statement 2 for (var i=0,len=cars.length;; i+++ "<br>"); Break }// If Statement 2 is omitted, the default is true, which causes an infinite loop, so that the browser crashes, always add a break at the appropriate location
// Omit Statement 3 var i=0,len=cars.length; for (; i<+ "<br>"); I+ +;}
Iv. for in
Create:
<script>function myFunction () {var x; var txt= ""; var person={fname: "Bill", lname: "Gates", age:56 for the person ) {txt= txt + person[x]+ ' <br> ';} document.getElementById ("Demo"). innerhtml=txt;} </script>// results:billgates56
V. While
Grammar:
while (condition) { code to execute }
PS: Also note that infinite loops cause the browser to collapse
Vi. do and
Grammar:
Do { The code to execute }while (condition);
PS: Almost the same as while, the only difference is that does while executing the statement, and then judge, so at least once. Also note that infinite loops cause the browser to collapse.
JS Basic ⑤