Are you familiar with the use of the control flow of JavaScript programs? Here we will describe the common control flow structures and statements of JavaScript programs, including the if condition statements, for statement and while LOOP statement.
JavaScript Program Control Flow
In any language, the control flow of a program is required. It can reduce the entire program and make it run smoothly in a certain way. The following are common JavaScript program control flow structures and statements:
1. if Condition Statement
Basic Format:
If Statement)
Statement segment 1;
......
Else
Statement Segment 2;
.....
Function: If the expression is true, statement segment 1 is executed; otherwise, statement Segment 2 is executed.
NOTE: if-else statements are the most basic control statements in JavaScript. They can be used to change the execution sequence of statements. The relational statement must be used in the expression for judgment. It is used as a Boolean value.
To estimate. It converts zero and non-zero numbers to false and true, respectively. If the statement after if has multiple rows, you must enclose it with curly brackets.
Nested format of if statement:
If Boolean) Statement 1;
Else Boolean value) Statement 2;
Elseif Boolean value) Statement 3;
......
Else Statement 4;
In this case, the Boolean expression of each level is calculated. If it is true, the corresponding statement is executed. Otherwise, the else statement is executed. Let's look at an instance.
Ifyuju.htm
- <Html>
- <Head>
- <Title> JavaScript program control flow If statement applet </title>
- <Script
- Language = "JavaScript">
- Varactivedate = newDate ();
- Activehour = activedate. getHours ()
- If (activehour <12 ){
- Document. write ("good morning" + "<br> ")
- } Else {
- Document. write ("Good afternoon" + "<br> ")
- }
- </Script>
- </Head>
- <Body>
- </Body>
- </Html>
Note: In this example, we first define a variable activedate and use the newDate function to get the current time, and then use the variable activehour to get the current hour, compare with 12 to determine whether it is "Morning" or "Afternoon" and then use the If statement to execute the corresponding statement program, that is, "good morning" or "Good afternoon ".