开发者

Bizarre console.log behaviour in Chrome Developer Tools [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Is Chrome's JavaScript console lazy about evaluating arrays?

Open up Chrome Developer Tools and type in:

var a = [];console.log(a);a.push(1);console.log(a);

You would expect this to output something like

[]
[1]

But instead it outputs

[1]
[1]

The behaviour is the same for

var a = [];console.log(a);a[0] = 1;console.log(a);

Can anyone explain this behav开发者_如何学编程iour?

Running Chrome on OS X. Same behaviour on 32bit Windows 7.

EDIT: The behaviour is the same regardless of whether the statements are on the same line or not. I have simply provided them on a single line to make it easy to test.

Putting

var a = [];
console.log(a);
a.push(1);
console.log(a);

in a file then running it yields the same behaviour.

EDIT x 2 See: http://jsfiddle.net/9N4A6/ if you don't feel like making a file to test.


Try this instead:

var a = []; console.log(a.toString()); a.push(1); console.log(a.toString());

It's not that the order of evaluation is strange, I bet, but that the conversion of the objects to printable form happens after the statements are all executed, at the point when Chrome is ready to actually dump out the log.


Same behavior here with Win7 on a x64 machine. My guess is that the log method holds a reference to a and queues the calls that happen to be in a single line.

EDIT It's not a Chrome/ium issue alone, I have witnessed the same with Firebug. As I said console logging must be queued in some ways.


What's being "logged" is the object "a"... not the plain text representation of "a". The log display is clever enough to display a place holder for object "a", which gets filled in/populated "later" (seems like at the end of the event invocation). If you stick an alert() statement in you'll see the values you expect (logged values get "filled in"):

var a = [];
console.log(a);
alert('force console to display correctly');
a.push(1);
console.log(a);

This seems like a bug in Chrome to me (kinda goofy to have to put an alert statement in to see the correct logging information).

(note this question showed at the top of a google search for "console.log chrome only shows current values" so I thought I'd add my answer)


At least with arrays, you can clone the array for each log call:

var a = [];console.log([].concat(a));a.push(1);console.log([].concat(a));

For objects, I recommend JSON:

var a = {};console.log(JSON.stringify(a));a[0]=1;console.log(JSON.stringify(a));


Yeah it does that on objects too....and if you change the value later (say, many seconds later) and then expand the object in the console, the new value will be in there. Weird, but can be useful in a sense.

If you want the current value, just say "console.log(a.toString());" or the like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜