对象的奇怪行为&控制台日志 [英] Weird behavior with objects & console.log

查看:30
本文介绍了对象的奇怪行为&控制台日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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));

这篇关于对象的奇怪行为&控制台日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆