Console.log() 和 settimeout(fn, 0)

Console.log() and settimeout(fn, 0)

我对 运行 在 Chrome 控制台中的以下代码有几个问题(我强调了每个循环之间的区别)。代码的意图是立即打印出偶数,然后按顺序打印出奇数(因为堆栈是清晰的,并且 Chrome 通过事件队列开始 运行ning ,从我明白)。

  1. 第一次循环,为什么显示undefined?为什么undefined左边有个小

  2. 对于第二个循环,为什么1在它打印的地方打印?看起来这是控制台正在做的事情,而不是我的代码。

  3. 第二个循环,为什么打印出来的是2? for 循环严格小于 2.

  4. 为什么第三个循环打印undefined3?控制台实际上没有在 符号旁边打印出数字有什么不同?

  5. 最后一个循环,为什么13没有打印出来?有点像它打印了 4 3 次。

  6. 你是如何使用setTimeout实现我的代码意图的?

如果您自己尝试代码,似乎每次 运行 循环时 旁边的数字都会递增。

您需要使用Immediately Invoked Function Expression(IIFE)来绑定i

的当前值

示例:

for( var i = 0 ; i < 5 ; i++) {
    if(i % 2 == 0) {
        console.log(i);
    } else {
        (function(_i) {
            setTimeout(function() { console.log(_i); }, 0);
        })(i);
    }
}

For the first loop, why does it show undefined? Why is there the little on the left of undefined?

<- 表示 return 值。该代码没有 return 任何内容。

For the second loop, why does 1 print where it does? It looks like this is something the console is doing, not my code.

这里,代码做了 return 事情:1。即setTimeout.

的ID

For the second loop, why does 2 print out? The for loop is for strictly less than 2.

参见 JavaScript closure inside loops – simple practical example——当您的代码 运行 时,i 现在为 2。

Why does the third loop print undefined and 3? What's different that the console didn't actually print out a number next to the <· symbol?

undefined 是由循环编辑的最后一个值 return -- console.log() 的值。 3 登录超时。

For the last loop, why didn't 1 and 3 print? Kind of seems like it printed 4 3 times.

How do you accomplish the intent of my code using setTimeout in this way?

再看JavaScript closure inside loops – simple practical example