console.dir 和 console.log 有什么区别? [英] What's the difference between console.dir and console.log?
问题描述
在 Chrome 中,console
对象定义了两个似乎做同样事情的方法:
In Chrome the console
object defines two methods that seem to do the same thing:
console.log(...)
console.dir(...)
我在网上某处读到 dir
在记录之前获取对象的副本,而 log
只是将引用传递给控制台,这意味着当你去的时候要检查您记录的对象,它可能已更改.然而,一些初步测试表明没有区别,并且它们都可能显示处于与记录时不同状态的对象.
I read somewhere online that dir
takes a copy of the object before logging it, whereas log
just passes the reference to the console, meaning that by the time you go to inspect the object you logged, it may have changed. However some preliminary testing suggests that there's no difference and that they both suffer from potentially showing objects in different states than when they were logged.
在 Chrome 控制台中试试这个 (Ctrl+Shift+J) 看看我的意思:
Try this in the Chrome console (Ctrl+Shift+J) to see what I mean:
> o = { foo: 1 }
> console.log(o)
> o.foo = 2
现在,展开 log 语句下方的 [Object]
并注意它显示 foo
的值为 2.如果您使用dir
而不是 log
.
Now, expand the [Object]
beneath the log statement and notice that it shows foo
with a value of 2. The same is true if you repeat the experiment using dir
instead of log
.
我的问题是,为什么console
上会存在这两个看似相同的功能?
My question is, why do these two seemingly identical functions exist on console
?
推荐答案
在 Firefox 中,这些函数的行为完全不同:log
只打印出一个 toString
表示,而 dir
打印出一个可导航的树.
In Firefox, these function behave quite differently: log
only prints out a toString
representation, whereas dir
prints out a navigable tree.
在 Chrome 中,log
已经打印出一棵树——大部分时间.然而,Chrome 的 log
仍然对某些类的对象进行字符串化,即使它们有属性.也许最明显的差异示例是正则表达式:
In Chrome, log
already prints out a tree -- most of the time. However, Chrome's log
still stringifies certain classes of objects, even if they have properties. Perhaps the clearest example of a difference is a regular expression:
> console.log(/foo/);
/foo/
> console.dir(/foo/);
* /foo/
global: false
ignoreCase: false
lastIndex: 0
...
您还可以看到数组(例如,console.dir([1,2,3])
)与普通对象log
的明显区别:
You can also see a clear difference with arrays (e.g., console.dir([1,2,3])
) which are log
ged differently from normal objects:
> console.log([1,2,3])
[1, 2, 3]
> console.dir([1,2,3])
* Array[3]
0: 1
1: 2
2: 3
length: 3
* __proto__: Array[0]
concat: function concat() { [native code] }
constructor: function Array() { [native code] }
entries: function entries() { [native code] }
...
DOM 对象也表现出不同的行为,如另一个答案所述.
DOM objects also exhibit differing behavior, as noted on another answer.
这篇关于console.dir 和 console.log 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!