javascript while loop giving different results in node and browser

后端 未结 2 578
野趣味
野趣味 2021-01-27 10:49

I am executing the following seemingly straightforward code

var number = 0;
while (number <= 12) {
    console.log(number);
    number = number + 2;  
}


        
相关标签:
2条回答
  • 2021-01-27 11:23

    If you run a script in Firebug's console, then it will evaluate the code. So it's evaluating the value of the last number in the while loop (which is now 14) and prints that out. It's actually printing out the value of number 8 times but groups them in 1 print out.

    You can see the same effect by just typing in "window" in the command line. It's evaluating it's value and prints it out in the console.

    More info can be found in the description to Firebug's command line.

    0 讨论(0)
  • 2021-01-27 11:40

    If you slightly change your code:

    CHROME

    var number = 0;
    while (number <= 12) {
        console.log("z" + number);
        number = number + 2;  
    }
    
    z0
    z2
    z4
    z6
    z8
    z10
    z12
    14
    

    You'll see that the 14 is not being printed by the loop. Rather, that is the end value of the expression when the loop finishes running and is printed by the console itself.

    FIREFOX

    while (number <= 12) {
        console.log("z" + number);
        number = number + 2;  
    }
    
    14
    "z0"
    "z2"
    "z4"
    "z6"
    "z8"
    "z10"
    "z12"
    

    In Firefox, it runs the entire loop, prints the result and then catches up with the console.

    0 讨论(0)
提交回复
热议问题