对象的奇怪行为控制台日志

2022-01-29 00:00:00 object google-chrome javascript

这段代码:

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 中产生以下输出:

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]

小提琴:http://jsfiddle.net/2kpnV/

这是为什么呢?

推荐答案

通过 console.log 检查对象以异步方式发生.控制台同步接收对对象的引用,但在对象展开之前不会显示对象的属性(在某些情况下,取决于浏览器以及日志发生时是否打开了开发工具).如果在控制台中检查对象之前已对其进行了修改,则显示的数据将具有更新后的值.

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.

例如,Chrome 会在一个框中显示一个小 i,当鼠标悬停时,会显示:

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.

让你知道你在看什么.

在这些情况下记录的一个技巧是记录单个值:

One trick for logging in these cases is to log the individual values:

console.log(obj.foo, obj.bar, obj.baz);

或 JSON 编码对象引用:

Or JSON encode the object reference:

console.log(JSON.stringify(obj));

相关文章