Google Chrome console.log out of sequence? [duplicate]

老子叫甜甜 提交于 2019-11-29 07:28:51

console.log is always a little "late" and you can't count on it when it comes to objects. Only primitives (strings etc.) will work directly. Of the former there is only one instance in memory, so when the console is fetching the data it may have changed already.

Of course, it depends on which console you're actually using, but I'm frequently experiencing this on Chrome.

Here is someone who experienced this on Firebug.

Am I right in thinking you're using Chrome? Firebug doesn 't do this (I just checked - FF8.0, FB 1.8.4) but Chrome 16 does.

I think what's happening is that in Chrome, the console.log() is executed asynchronously, so as not to interrupt your code or something; effectively, all the console.log()s happen at once after the code that called them has finished running.

Edit: curses, ninja'd!

The behavior of console.log

The console.log snapshots element in the execute scope and print them in the console. An demonstration is here:

(function () {
  console.log(obj);
  var obj= {};
  obj.new_value = 'hello';
}())

obj is not defined when console.log is called. But it is printed into the console with the right property new_value.

The problem with firefox

First, when use function keyword to declare a function in firefox, the name of the function won't be assigned until execution of the code.

If you didn't define loadNextItem in your previous code, the following code will generate an error(ReferenceError: loadNextItem is not defined) in firefox.

loadNextItem();

function loadNextItem (){
    var item = itemsAry.shift();
    console.log(item);
}

This behavior is stated in ECMA-262

Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations.

And firefox doesn't support this behavior.

Unable to duplicate in FF 8.0 using

x = [1,2,3,4,5];
console.log(x);
y();
function y() {
    z = x.shift();
    console.log(z);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!