如何检查Javascript对象 [英] How to inspect Javascript Objects

查看:119
本文介绍了如何检查Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在警告框中检查对象?通常警告对象只会抛出节点名称:

How can I inspect an Object in an alert box? Normally alerting an Object just throws the nodename:

alert(document);

但我想在警告框中获取对象的属性和方法。如果可能,我该如何实现此功能?或者还有其他建议吗?

But I want to get the properties and methods of the object in the alert box. How can I achieve this functionality, if possible? Or are there any other suggestions?

特别是,我正在为没有console.log和Firebug的生产环境寻求解决方案。

Particularly, I am seeking a solution for a production environment where console.log and Firebug are not available.

推荐答案

中的 - 中的循环对象或数组中的每个属性。您可以使用此属性来获取值并更改它。

The for-in loops for each property in an object or array. You can use this property to get to the value as well as change it.

注意:除非您有私人财产,否则无法进行检查使用间谍;基本上,你覆盖对象并编写一些在对象上下文中执行for-in循环的代码。

Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.

对于看起来像:

for (var property in object) loop();

一些示例代码:

function xinspect(o,i){
    if(typeof i=='undefined')i='';
    if(i.length>50)return '[MAX ITERATIONS]';
    var r=[];
    for(var p in o){
        var t=typeof o[p];
        r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+'  ') : o[p]+''));
    }
    return r.join(i+'\n');
}

// example of use:
alert(xinspect(document));

编辑:前段时间,我写了自己的检查员,如果你我很感兴趣,我很乐意分享。

Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.

编辑2:好吧,无论如何我写了一篇。

Edit 2: Well, I wrote one up anyway.

这篇关于如何检查Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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