Weird behavior with objects amp; 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 中产生以下输出:
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));
这篇关于对象的奇怪行为控制台日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象的奇怪行为控制台日志
- 如何显示带有换行符的文本标签? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01