How to inspect Javascript Objects

后端 未结 8 535
半阙折子戏
半阙折子戏 2020-12-07 10:31

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 p

相关标签:
8条回答
  • 2020-12-07 11:00

    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.

    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 in looks like:

    for (var property in object) loop();
    

    Some sample code:

    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));
    

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

    Edit 2: Well, I wrote one up anyway.

    0 讨论(0)
  • 2020-12-07 11:03

    How about alert(JSON.stringify(object)) with a modern browser?

    In case of TypeError: Converting circular structure to JSON, here are more options: How to serialize DOM node to JSON even if there are circular references?

    The documentation: JSON.stringify() provides info on formatting or prettifying the output.

    0 讨论(0)
提交回复
热议问题