How can I change the default behavior of console.l

2018-12-31 05:07发布

In Safari with no add-ons, console.log will show the object at the last state of execution, not at the state when console.log was called.

I have to clone the object just to output it via console.log to get the state of the object at that line.

Example:

var test = {a: true}
console.log(test); // {a: false}
test.a = false; 
console.log(test); // {a: false}

11条回答
爱死公子算了
2楼-- · 2018-12-31 05:29

What I usually do if I want to see it's state at the time it was logged is I just convert it to a JSON string.

console.log(JSON.stringify(a));
查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 05:30

That > Object in the console, isn't only showing the current state. It actually is deferring reading the object and it's properties until you expand it.

For example,

var test = {a: true}
console.log(test);
setTimeout(function () {
    test.a = false; 
    console.log(test);
}, 4000);

Then expand the first call, it will be correct, if you do it before the second console.log returns

查看更多
有味是清欢
4楼-- · 2018-12-31 05:32

You might want to log the object in a human readable way:

console.log(JSON.stringify(myObject, null, 2));

This indents the object with 2 spaces at each level.

How can I pretty-print JSON using JavaScript?

查看更多
何处买醉
5楼-- · 2018-12-31 05:35

Just print whole object on console.

console.dir(object);
查看更多
无与为乐者.
6楼-- · 2018-12-31 05:37

I may be shot for suggesting this, but this can be taken one step further. We can directly extend the console object itself to make it more clear.

console.logObject = function(o) {
  (JSON.stringify(o));
}

I don't know if this will cause some type of library collision/nuclear meltdown/rip in the spacetime continuum. But it works beautifully in my qUnit tests. :)

查看更多
登录 后发表回答