简体   繁体   中英

Where is this final number coming from?

If I run the following code in Chrome console (apologies for the label):

var x = 0;

theLoop:
    while (1) {

        if (!(x <= 2)) {
            break theLoop;
        }

        console.log('x: ', x);
        ++x;
        continue theLoop;
    }

The following is output to the console:

x:  0
x:  1
x:  2
3

It's late, so I'm missing something very obvious, but where is the '3' coming from?

Don't worry about that: it is not an actual console.log, but just your browser that displays the last value that has been read (unless it is assigned to a var ), in this case the ++x that equals 3.

For instance if at the end of your snippet you add console.log('the end'); or even just 0; the last log will be different, yet won't affect your program.

It looks like Chrome by default prints the last assigned variable, but only when it was assigned at least twice, so this:

 var x = 5; var y = 3; 

will result with nothing, but

var x = 5;
x = 4;
var y = 3;

will give you 4 .

In your case it was x=3

I have seen such too. But the value is not used in application. Firefox won't display it.

好的,所以3是控制台在循环后返回x值,原因x == 3是在显示x: 2行之后, ++x再次递增x ,ergo x == 3

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