奇怪的行为与对象&的console.log [英] Weird behavior with objects & console.log
问题描述
此代码:
foo = [{id:1},{id:2},{id:3} ,{id:4},{id:5},];
console.log('foo1',foo,foo.length);
foo.splice(2,1);
console.log('foo2',foo,foo.length);
在Chrome中产生以下输出:
<$
$ {code $ f $ $ $ $ $ $ $ $ $ $ $ $ $ $' $ b 3:Object
length:4
__proto__:Array [0]
5(index):23
foo2
[Object,Object,Object,Object] 4
0:Object
1:Object
2:Object
3:Object
length:4
__proto__:Array [0]
小提琴: http ://jsfiddle.net/2kpnV/
为什么会这样?
console.log
检查对象是以异步方式进行的。控制台同步接收对象的引用,但在展开之前不显示对象的属性(在某些情况下,取决于浏览器以及日志发生时是否打开开发工具)。如果在控制台检查对象之前对象已被修改,则显示的数据将具有更新后的值。例如,Chrome会显示一些>
在一个盒子里,当它盘旋时,说:
当记录时,左侧的对象值被快照,价值低于刚才评估。
让你知道你在看什么。
记录这些情况的一个技巧是记录单个值,或者JSON编码对象引用:
console.log(obj.foo,obj.bar,obj.baz);
//或
console.log(JSON.stringify(obj));
This code:
foo = [{id: 1},{id: 2},{id: 3},{id: 4}, {id: 5}, ];
console.log('foo1', foo, foo.length);
foo.splice(2, 1);
console.log('foo2', foo, foo.length);
Produces the following output in Chrome:
foo1
[Object, Object, Object, Object, Object] 5
0: Object
1: Object
2: Object
3: Object
length: 4
__proto__: Array[0]
5 (index):23
foo2
[Object, Object, Object, Object] 4
0: Object
1: Object
2: Object
3: Object
length: 4
__proto__: Array[0]
Fiddle: http://jsfiddle.net/2kpnV/
Why is that?
Examining objects via console.log
happens in an asynchronous manner. The console receives a reference to the object synchronously, but does not display the properties of the object until it is expanded (in some cases, depending on the browser and whether you have dev tools open when the log happens). If the object has been modified before examining it in the console, the data shown will have the updated values.
For example, Chrome will show a little i
in a box which, when hovered, says:
Object value at left was snapshotted when logged, value below was evaluated just now.
to let you know what you're looking at.
One trick for logging in these cases is to log the individual values, or JSON encode the object reference:
console.log(obj.foo, obj.bar, obj.baz);
//or
console.log(JSON.stringify(obj));
这篇关于奇怪的行为与对象&的console.log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!