How to inspect Javascript Objects

后端 未结 8 543
半阙折子戏
半阙折子戏 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 10:42

    This is blatant rip-off of Christian's excellent answer. I've just made it a bit more readable:

    /**
     * objectInspector digs through a Javascript object
     * to display all its properties
     *
     * @param object - a Javascript object to inspect
     * @param result - a string of properties with datatypes
     *
     * @return result - the concatenated description of all object properties
     */
    function objectInspector(object, result) {
        if (typeof object != "object")
            return "Invalid object";
        if (typeof result == "undefined")
            result = '';
    
        if (result.length > 50)
            return "[RECURSION TOO DEEP. ABORTING.]";
    
        var rows = [];
        for (var property in object) {
            var datatype = typeof object[property];
    
            var tempDescription = result+'"'+property+'"';
            tempDescription += ' ('+datatype+') => ';
            if (datatype == "object")
                tempDescription += 'object: '+objectInspector(object[property],result+'  ');
            else
                tempDescription += object[property];
    
            rows.push(tempDescription);
        }//Close for
    
        return rows.join(result+"\n");
    }//End objectInspector
    

提交回复
热议问题