简体   繁体   English

这个最终号码来自哪里?

[英]Where is this final number coming from?

If I run the following code in Chrome console (apologies for the label): 如果我在Chrome控制台中运行以下代码(标签道歉):

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? 已经很晚了,所以我错过了一些非常明显的东西,但'3'来自哪里?

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. 不要担心:它不是一个真正的console.log,而只是显示已读取的最后一个值的浏览器(除非它被分配给var ),在这种情况下, ++x等于3。

For instance if at the end of your snippet you add console.log('the end'); 例如,如果在您的代码段的末尾添加了console.log('the end'); or even just 0; 甚至只是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: 默认情况下,Chrome会显示最后指定的变量,但只有在至少分配两次时才会这样,所以这样:

 var x = 5; var y = 3; 

will result with nothing, but 什么都没有,但是

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

will give you 4 . 会给你4

In your case it was x=3 在你的情况下,它是x=3

I have seen such too. 我也见过这样的。 But the value is not used in application. 但该值未在应用程序中使用。 Firefox won't display it. Firefox不会显示它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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