如何让 console.log 显示对象的当前状态? [英] How can I make console.log show the current state of an object?

查看:39
本文介绍了如何让 console.log 显示对象的当前状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有附加组件的 Safari 中(实际上是大多数其他浏览器),console.log 将显示最后执行状态的对象,而不是 console.log 时的状态 被调用.

In Safari with no add-ons (and actually most other browsers), console.log will show the object at the last state of execution, not at the state when console.log was called.

我必须克隆该对象,以便通过 console.log 输出它以获取该行对象的状态.

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

示例:

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

推荐答案

我认为您正在寻找 console.dir().

console.log() 不会执行您想要的操作,因为它打印了对对象的引用,而当您将其打开时,它已更改.console.dir 打印对象中调用它时的属性目录.

console.log() doesn't do what you want because it prints a reference to the object, and by the time you pop it open, it's changed. console.dir prints a directory of the properties in the object at the time you call it.

下面的 JSON 想法很好;你甚至可以继续解析 JSON 字符串并获得一个可浏览的对象,就像 .dir() 会给你的:

The JSON idea below is a good one; you could even go on to parse the JSON string and get a browsable object like what .dir() would give you:

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

这篇关于如何让 console.log 显示对象的当前状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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