Javascript 反射 - 通用 toString

发布于 2024-12-23 10:10:49 字数 116 浏览 3 评论 0原文

现在,当我将自己的对象放入警报功能时,我看到

[对象对象]

即是无意义的信息。有没有办法使用反射来获取所有字段以及这些字段的值?

now when I put my own Object in alert function I see

[Object object]

that is pointless information. is there any way using reflection to get all fields and values of those fields?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦冥 2024-12-30 10:10:49

JSON.stringify 通常是内置的,可以序列化您传递给它的大多数对象。

也就是说,您可能应该只使用调试器或 console.log,而不是发出警报。

JSON.stringify is often times builtin and can serialize most objects you pass to it.

That said, you should probably just use a debugger or console.log instead of alert-ing things.

罪歌 2024-12-30 10:10:49

这是其中之一。但最好使用 console.log() 然后使用 alert

function objectToString(o){
    var parse = function(_o){
        var a = [], t;
        for(var p in _o){
            if(_o.hasOwnProperty(p)){
                t = _o[p];
                if(t && typeof t == "object"){
                    a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
                }
                else {
                    if(typeof t == "string"){
                        a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
                    }
                    else{
                        a[a.length] = [ p+ ": " + t.toString()];
                    }
                }
            }
        }
        return a;
    }
    return "{" + parse(o).join(", ") + "}";
}

Here is one of many. But better to use console.log() then alert

function objectToString(o){
    var parse = function(_o){
        var a = [], t;
        for(var p in _o){
            if(_o.hasOwnProperty(p)){
                t = _o[p];
                if(t && typeof t == "object"){
                    a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
                }
                else {
                    if(typeof t == "string"){
                        a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
                    }
                    else{
                        a[a.length] = [ p+ ": " + t.toString()];
                    }
                }
            }
        }
        return a;
    }
    return "{" + parse(o).join(", ") + "}";
}
拥抱影子 2024-12-30 10:10:49

当然,也许像

function alertObject(0){
    var str = "";
    for(i in o)
        str += i + " " + o[i] + "\n";
    alert(str);
}

编辑::注意这只是一个愚蠢的小例子。

sure, maybe something like

function alertObject(0){
    var str = "";
    for(i in o)
        str += i + " " + o[i] + "\n";
    alert(str);
}

Edit :: Note this is just a silly little example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文