为什么我的 while 循环会以这种方式记录?

Why is my while loop getting logged this way?

为什么我的 while 循环会以这种方式记录?是因为 V8 和 SpiderMonkey 的内部工作原理不同吗?

var counter = 0;
while (counter <= 10) {
    console.log(counter);
    counter++;
}

注意:在 Chrome 和 Firefox 控制台中尝试上面的代码。

这些是我执行上述代码时得到的结果。

在Chrome中:

在 Firefox 中:

为什么记录的结果不同?这是怎么回事?

是的,内部运作方式不同。我相信您在这里注意到的区别实际上是因为在 WebKit 浏览器中,例如 Chrome 和 Safari,console.log 是异步的,而在 Firefox(和 Node.js)中它是严格同步的。

我第一次在 Trevor Burnham 的 Async JavaScript 一书中读到这一点。您可以转到此 Google Books search link for Async JavaScript 找到本书的相关部分,相关页面应该是顶部的第一个响应。

WebKit's console.log has surprised many a developer by behaving asynchronously.

为了帮助理解发生了什么,请尝试在控制台中输入以下内容:

var counter = 0
while (counter <= 10) { counter ++ }

您会看到,这自然会 return 自身的 10 值。这只是 while 循环结束时 counter 的最终值。因此,因为 console.log 在 Firefox 中是同步的,所以 console.log 语句同时开始 while 循环 10 的 return 值是 return编辑。因为它在 Chrome 中是异步的,while 循环的 return 值等待 return,直到所有 console.log 调用完成。 Chrome 和 Firefox 之间 console.log 的同步性质的差异正在改变这个值是同时 returned 还是在所有 console.log 调用之后。这就是您注意到的差异的本质。

如果您仍然感到困惑,我建议您阅读异步代码的概念。这是一个中级概念,所以如果您刚刚开始并且还没有完全掌握它也没关系。上面引用的书是很好的资源,但您可以在 Mozilla 开发人员网络上开始学习基础知识。以下是来自 MDN 的一些资源,可作为异步编程的入门资料: