简体   繁体   中英

Javascript for loop displaying more results than expected

When running the code below, the text inside the document.write runs 8 times and not 7 times as I was expected.

If I understand correctly, increment by 2 should display the positions:
20+2, 22+2, 24+2, 26+2, 28+2, 30+2 and 32+2 .

Based on the results I get I assume it also displays the 34+2, which is 36. What I am missing? Thank you.

 x = 20;
 for (x = 20; x < 35; x += 2) {
   document.write("How many times will this loop execute?" + "<br/>");
 };

As noted in the comments above, The loop is correct in running 8 times. Since no one stated the reason, it is this: the x+=2 happens at the end of the loop, not at the beginning. So the loop will run for 20, 22, 24, 26, 28, 30, 32, and 34.

You are misunderstanding how the for loop works.

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

final-expression: An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.

So your counter gets incremented at the end of the loop and the observed behaviour is correct. The loop gets executed for 20, 22, 24, 26, 28, 30, 32, and 34.

It will run eight times, x iterating through every even number between 20 and 34 inclusive. You can write it like this if it helps:

var x = 20;
while (x <= 34) {
    // do something
    x += 2;
}

However, it is important to note that after the loop has run (whether you're using the for or while version), x will equal 36, since it is incremented to that before it finally fails the test; inside the loop, x will never equal 36. In terms of best practice, you should only really use a counter variable like x within the loop; this can be enforced by using the ES6 let keyword (which is block-scoped) like so (the example just prints out a list of the x values as DOM elements):

 function appendSpanCounter(i, end) { let el = document.createElement("span"), content = i.toString(10); if (i < end) content += ", "; (typeof el.textContent === "string") // ternary operator ? el.textContent = content : el.innerText = content; (document.body || document.querySelector("body")).appendChild(el); } for (let x = 20; x <= 34; x += 2) { appendSpanCounter(x, 34); } // x is now undefined here 

When start loop add +2 to x like below:

 x = 20;
 for (x = 20+2; x<35; x+=2) {
        document.write("How many times will this loop execute?" + "<br/>");
    };

fiddle

Script:

x = 20;
count = 1;
for (x = 20; x < 35; x += 2){
  document.write("Execution: "+ (count++)+ "<br/>");
};

Output

The loop executes total 8 times.

 Execution: 1 Execution: 2 Execution: 3 Execution: 4 Execution: 5 Execution: 6 Execution: 7 Execution: 8 

jsfiddle link to checkout.

Yes, is executing 8 times, because is from 20 to 35 in 2 x 2

 x = 20; for (x = 20; x < 35; x += 2) { document.write("Execute for " + x + " " + "<br/>"); }; /* OUTPUT: Execute for 20 Execute for 22 Execute for 24 Execute for 26 Execute for 28 Execute for 30 Execute for 32 Execute for 34 */ 

If you want 7 times, you can change to 34

  x = 20; for (x = 20; x < 34; x += 2) { document.write("Execute for " + x + " " + "<br/>"); }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM