Javascript-for-loop-example--reference

Source: Internet
Author: User

We hear a lot about loops, especially for loops. Why, in fact, is they? They ' re just pieces of code that repeat the same commands several times, until you reach a desired conclusion, without get Ting bored out of your mind, repeating your code. This is what we JavaScript guys do it.






Syntax

You'll definitely has the know the syntax of for loops and that goes as this:

1 for([initialization]; [condition]; [final-expression]) statement

You'll see in the examples what each of the these clauses are translated into code. So let's start right away.

Using Simple forLoops

The most typical for -loops is counting. You just need to tell the loop where to start, where to finish, and with what pace to count. This is what the code goes for counting and printing in the screens odd numbers from one to ten:

1 for(vari = 1; i < 10; i+2) {
2     console.log(i);
3 }

According to the syntax structure we gave your above, you can now easily distinguish so we have first declared and Initia Lized the variable with the value 1. We have the set of the condition, which in we are to not count odd numbers greater than, and the final one is the pace, a nd since the closest odd numbers only differ by 2 the final expression is i+2 . Notice that we start the loop with an odd number.

removing forLoop ' s clauses

One-to-put for loops in good use would is to optimize them, by removing the expressions. Each one of them can is omitted, or you can even omit them all. We'll be using the same code of the example above, only we'll modify it according to the thing we want to show you, so t Hat you can draw the differences and understand it more. Firstly, we'll show you where and how can you remove the initialization expression. There is a look at the IT changes:

1 vari = 1;
2 for(; i < 10; i+2) {
3     console.log(i);
4 }

You'll definitely notice that we had removed the initialization expression, but the variable is initialized outside the Loop before we write the code for the loop. Also What's important here's the place where the expression we removed were is still there, even though it's now empt Y. It's not correct to remove the semicolon saving that space.

Now it's time to show what you do to use a for loop with all three blocks removed. This is the code:

1 i=0;
2 for(;;) {
3     if(i > 3) break;
4     console.log(i);
5     i++;
6 }

You is obliged to declare an initialize the variable before writing the rest of the loop ' s code. If you don't want to put a condition or a by-a-to-get out of the loop, you would is building an infinite loop. But if it's not your intention then you'll have to put a condition and an expression that changes the value of the VA Riable, as we have the do in the previous code snippet.

forLoops and Break ;

If you were careful in watching the code snippets above you'll see something so we did not explain:the expression . That expression was used to jump out of the loop, which means that it takes the command right after the loop, without Execu Ting the rest of it, but instead doing whatever code is next. Here's an example's how can use it:

1 vartext = ""
2 vari;
3 for(i = 0; i < 10; i++) {
4     if(i == 3) {break;}
5     text += "The number is "+ i + "<br>";
6 }

This code snippet prints out the value of the I variable, and increments it by one. When the value of I is reaches 3, it breaks out of the loop. That's how the break; expression operates.

forLoops and continue;

continue; break; The expression is similar-only the breaks out of the current iteration, and into the next one, no T necessarily out of the loop. Here ' s the modified example:

1 vartext = ""
2 vari;
3 for(i = 0; i < 10; i++) {
4     if(i == 3) {continue;}
5     text += "The number is "+ i + "<br>";
6 }

Instead of We have used and the difference are, the next iteration to be executed are not the one after break; continue; th e Loop, it ' s the one after the iteration containing continue; .

for...inLoops

The for...in loops is a-iterating only the properties of different objects. It ' s sytax is like this:

1 for(var variable inobjectExpression) {statement}

Any expression that is evaluates to an object can is used objectExpression as, and this object ' s properties is the ones to be iterated. On each iteration, the property names was assigned to variables, and then the statement was executed. See the example below:

1 varmyObj = {a: 1, b: 2, c: 3},
2     myKeys = [];
3  
4 for(var property inmyObj) {
5     myKeys.push(property);
6 }
7  
8 myKeys;
9
10 //[‘a‘,‘b‘,‘c‘];

Note that the properties ' values is actually strings, so whatever action you want to does with, or on them in the statement block, you'll have the to think of them as such.

Using forWith an empty statement

The awesome part on JavaScript is so almost every modification of the code leads you somewhere useful. That's the case with the following code, which we ' d like you to see First and discuss later:

1 functionshowOffsetPos (sId) {
2
3     // initialization
4     varnLeft = 0, nTop = 0;
5
6     // condition
7     for(varoItNode = document.getElementById(sId);
8         // final-expression
9          oItNode;
10          nLeft += oItNode.offsetLeft,
11          nTop += oItNode.offsetTop,
12
13           // empty statement
14          oItNode = oItNode.offsetParent) ;
15
16     console.log("Offset position of \""+ sId + "\" element:\n left: "
17         + nLeft + "px;\n top: "+ nTop + "px;");
18 }
19
20 showOffsetPos("content");

This loop calculates the offset position of a node in the Final-expression section, therefore making the use of a statemen T block useless, so the empty statement is used instead.

Download the source code

This is an example of -loops in JavaScript.

http://www.webcodegeeks.com/javascript/javascript-for-loop-example/

Javascript-for-loop-example--reference

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.