Native JavaScript second article

Source: Internet
Author: User

 The program control statements in JS

There are three types of execution structures for common programs:

1. Sequential structure

2. Branching structure

3. Cyclic structure

Sequential structure: The program executes from the first line and executes sequentially to the last line

Branching structure: Like a fork, you have to choose and choose only one of the roads to continue, and you cannot execute code in two branches at the same time.

We can use the following three ways to implement the branch structure of the program

   if (condition) {expression}

   switch (variable) case expression; Break

   Expression 1? Expression 2: Expression 33-mesh operation

  If statement:

We can implement a branching structure through if. The IF statement requires two necessary content: Judging conditions and branching statements. Where the judging condition can only return a Boolean value, if the judging condition is true, then execute branch one, otherwise execute sub-two or skip if statement want to continue execution behind.

Dual-branch structure

  Example of an IF statement:

var age = 20; if (age >= 18) {//If Age >= 18 is true, the If statement block is executed

Alert (' adult ');

} Else {//Else execute else statement block

Alert (' teenager ');

}

The above example is a two-branch structure that executes the code in the first curly brace if the conditional expression in the parentheses is true, otherwise the code in the second curly brace is executed. Where the Else statement is optional, if there is no else statement, the judgment condition is not set to skip the branch and proceed backwards. Note: When the code in the branch is only one line, the curly braces can be omitted, but in order to avoid the confusion of the program and not easy to read, it is best not to omit it.

  Multi-branch structure

var age = 3; if (age >= 18) {

Alert (' adult ');

} Else if (age >= 6) {

Alert (' teenager ');

} Else {

Alert (' Kid ');

}

Or

var age = 3; if (age >= 18) {

Alert (' adult ');

} Else {

if (Age >= 6) {

Alert (' teenager ');

} Else {

Alert (' Kid ');

}

}

We can use nested If...else to implement multi-branch structure, please note that if...else ... The execution characteristic of the statement is two select one, in multiple if...else ... Statement, if a condition is true, subsequent judgments are no longer continued.

  Switch statement

In front of our learning branch structure is to learn if...else ... This structure, we can implement the multi-branch structure through the nesting of the IF statement, below will learn a more simple multi-branch statement: Switch...case ...

Grammar:

Switch (n)

{ Case 1:

Executing code block 1

break; Case 2:

Executing code block 2

break; default:

N Code that executes when it differs from Case 1 and 2

}

First, set the 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 the code from automatically running down a case, and if there is no break statement after the scenario, the program will fall into the next one until the first break is encountered or the case of the full part is stopped.

Exercise: Judging today is the day of the week, and the box shows

var day=New Date (). GetDay (); Switch (day)

{ case 0:

x= "Today it ' s Sunday";

break; Case 1:

x= "Today it ' s Monday";

break; Case 2:

x= "Today it ' s Tuesday";

break; Case 3:

x= "Today it ' s Wednesday";

break; Case 4:

x= "Today it ' s Thursday";

break; Case 5:

x= "Today it ' s Friday";

break; Case 6:

x= "Today it ' s Saturday";

break;

}

alert (x);

  Default keyword

You may have noticed that the syntax structure above is a default, a keyword. The primary task of this keyword is to execute the default branch when the last else branch in the IF statement does not match the conditions in front.

Example: If today is not Saturday or Sunday, the default message will be output:

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";

}

  For loop

  What is a loop?

The cycle of life is everywhere, such as: The clock keeps turning, the sun is constantly dongsheng West, the students run around to run the circle and so on. Repeated to do one thing, is the cycle, if the cycle does not stop the condition, then become a dead cycle, if the cycle reached the stop condition, the cycle ends, such as: clock no electricity, clock stop movement, students run enough of a certain number of laps, no longer run.

  When will we use the loop?

If the 1+2+3 is calculated, how should the program be represented?

var sum = 1 + 2 + 3;

What if we add from 11 to 10000? In this case, to write an addition expression is wasteful, we observe: The task is to repeat the addition operation, the only change is addend, so when the program needs to repeat a task, we can use the loop to complete the task for us.

JavaScript has a variety of looping statements, and today we are learning for loops.

  Syntax structure for A for loop

for (define a loop increment; a cyclic condition; a loop increment from plus one) {

Circulation body;

}

Let's analyze the loop structure:

   Loop increment: Define a variable here and assign the initial value (typically 0 or 1)

   Loop condition: This is a conditional expression that is used to determine whether the loop condition satisfies

   The loop is over. Excess self plus one: here the loop increment defined in the front adds an action

   Loop body: If the loop condition is established, the loop body is executed repeatedly, and the loop condition is not established.

This for loop only executes in the following order:

  

1. Define a loop increment

2. Determine if the cycle conditions are true

3. Set up the execution loop body/Not established then skip the loop body, continue to execute backwards

4. Loop increment self plus One

5. Judging whether the cyclic condition is established since the addition of one

6. Set up the execution loop body/Not established then skip the loop body, continue to execute backwards

7 .....

8 .....

9 .....

10. When the loop condition is encountered, end the loop and continue executing the code backwards

Note: We must have cyclic conditions when writing loops, otherwise the program will go into a dead loop.

Example: 1+2+3+ ... +1000:

var x = 0; var i;  for (I=1; i<=10000; i++) {

x = x + i;

}

X 50005000

Let's analyze the control conditions for the next for loop:

   I=1 This is the initial condition, the variable i is set to 1;

   i<=10000 This is the judgment condition, when satisfies the circulation, does not satisfy on exits the circulation;

   i++ This is the increment condition after each loop, because the variable i is incremented by 1 after each cycle, it will eventually exit the loop after several cycles without satisfying the judging condition i<=10000.

  Loop out statement

  Break: Jump out of the loop and continue backwards

<! DOCTYPE html><HTML>

<head>

<Meta charset= "Utf-8" >

<title></title>

</Head>

<body>

</Body>

<script type= "Text/javascript" >

for (var i=0; i<10; i++) {

alert (i);

if (i>5) {

break;

}

}

</script></html>

Above program, when output to 6 o'clock stop output, because 6>5, meet if condition, so jump out of the loop, continue to execute backwards

  Continue: End this cycle, turn on the next cycle

<! DOCTYPE html><HTML>

<head>

<Meta charset= "Utf-8" >

<title></title>

</Head>

<body>

</Body>

<script type= "Text/javascript" >

for (var i=0; i<10; i++) {

alert (i);

if (i>5) {

Break

continue;

}

Alert ("I execute after continue");

}

</script></html>

The above code starts with output 6 and no longer outputs "I'm executing after continue," but the numbers continue to output.

  Expansion: for...in cycle

A variant of the For loop is a for ... in loop, which loops through all the properties of an object in turn:

var o = {

Name: ' Jack ',

AGE:20,

City: ' Beijing '

};  for (Var key in O) {

alert (key); ' Name ', ' age ', ' City '

}

  The Checked property of input

In the study of HTML is we all know: after the input tag type is set to a checkbox, it is a check box, if the Checked property is true, then the marquee is selected, if the Checked property is set to False, the marquee is unchecked. Below, we use JS to set the state of the marquee.

Example code: By clicking the toggle button, the checkbox is selected to uncheck the effect

<! DOCTYPE html><HTML>

<head>

<Meta charset= "Utf-8" >

<title></title>

</Head>

<body>

<input type= "button" value= "Toggle" id= "Btn1"/>

<input type= "checkbox" id= "Ch1"/>

</Body>

<script type= "Text/javascript" >

var btn1 = document.getElementById ("btn1");

var ch1 = document.getElementById ("Ch1");

Btn1.onclick = function () {

if (ch1.checked) {

ch1.checked = false;

}Else{

Ch1.checked = true;

}

}

</script></html>

Exercise: Implement a "Select All", "reverse" effect for similar shopping carts

The sample code is as follows:

<! DOCTYPE html><HTML>

<head>

<Meta charset= "Utf-8" >

<title></title>

</Head>

<body>

<input type= "button" value= "Select All" id= "btn1"/>

<input type= "button" value= "reverse" id= "btn2"/>

<input type= "checkbox" id= "Ch1"/>

<ul id= "UL1" >

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

<li><input type= "checkbox"/></li>

</ul>

</Body>

<script type= "Text/javascript" >

var btn1 = document.getElementById ("btn1");

var btn2 = document.getElementById ("btn2");

var ch1 = document.getElementById ("Ch1");

var ul1 = document.getElementById ("Ul1");

var inputs = Ul1.getelementsbytagname ("input");//alert (inputs.length);

Btn1.onclick = function () {

for (var i=0; i<inputs.length; i++) {

Inputs[i].checked = true;

}

Ch1.checked = true;

}

Btn2.onclick = function () {

var num = 0;

for (var i=0; i<inputs.length; i++) {

if (Inputs[i].checked==false) {

num++;

}

inputs[i].checked =!inputs[i].checked;

}

if (num = = inputs.length) {

Alert ("OK");

}

}

</script></html>

  While loop

The For loop is useful for the initial and end conditions of a known loop. The For loop, which ignores the conditions above, makes it easier to see the logic of the loop, which is better with a while loop.

While Loop has only one judgment condition, the condition satisfies, then loops continuously, the condition does not satisfy the exit loop. For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:

var x = 0; var n = 99;  while (n > 0) {

x = x + N;

n = n-2;

}

X 2500

The loop internal variable n is continuously self-reducing until it becomes 1, and the while condition is no longer satisfied, and the loop exits.

  Do ... while loop

Do {...} while () loop, the only difference between it and the while loop is that instead of judging the condition at the beginning of each loop, the condition is judged at the completion of each loop:

var n = 0;  Do {

n = n + 1;

} while (n < 100);

N 100

Use the do {...} while () loop to be careful, the loop is performed at least 1 times, and the for and while loops may not execute at once.

Native JavaScript second article

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.