具有突变状态的JavaScript记录对象 [英] JavaScript logging object with mutating state

查看:152
本文介绍了具有突变状态的JavaScript记录对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此JavaScript代码...

This JavaScript code...

var o = {};
console.dir(o);
o.foo = "bar";
console.dir(o);

...导致显示两次相同的交互树输出:

< img src =https://i.stack.imgur.com/2XOBH.pngalt =两个对象与foo:bar显示>

此问题作为一个bug < a href =http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays>这里在Stack Overflow ,记录为 Chromium错误 WebKit (我想象其他地方)。

...results in the same interactive tree output shown twice:

This issue is discussed as a bug here on Stack Overflow, logged as a Chromium bug and WebKit (and I imagine elsewhere).

我理解这个实现原因是的情况,但它使调试有状态的对象硬(不使用交互式调试器)。在这种情况下,您需要查看每个日志调用中对象的不同状态,您使用什么策略来记录日志? JSON.stringify()?是否有一个可以使用的序列化控制台方法?

I understand the implementation reason that this is the case, but it makes debugging stateful objects hard (without using the interactive debugger). What strategy do you use for logging in such situations, where you need to see the differing states of the object in each log call? JSON.stringify()? Is there a console method for serialization that can be used?

推荐答案

我会解决这个问题,您正在记录,并将副本传递到console.dir()。这样的工作很好:

I would solve this by making a "deep copy" of what you are logging, and passing the copy to console.dir(). Something like this works pretty well:

function deep_copy(ref)
{
    var r;
    var i;

    if(isHash(ref))
    {
        r = {};
        for(i in ref)
                r[i] = deep_copy(ref[i]);
    }
    else if(isArray(ref))
    {
        r = [];
        for(i = 0; i < ref.length; i++)
            r[i] = deep_copy(ref[i]);
    }
    else
    {
        r = ref;
    }

    return r;
}

如果你不想这样做, code> JSON.stringify 是一个很好的解决方法,如果在浏览器中是原生的,不会更慢。

If you don't want to bother with something like this, then using JSON.stringify is a great workaround and won't be much slower if it's native in the browser.

console.dir(JSON.parse(JSON.stringify(o));

这篇关于具有突变状态的JavaScript记录对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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