如何检查Javascript对象

Val*_*ina 96 javascript object inspect

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

alert(document);
Run Code Online (Sandbox Code Playgroud)

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

特别是,我正在寻找一个生产环境的解决方案,其中console.log和Firebug不可用.

Tor*_*ker 191

如何alert(JSON.stringify(object))用现代的浏览器?

在这种情况下TypeError: Converting circular structure to JSON,这里有更多选项:如果有循环引用,如何将DOM节点序列化为JSON?

文档:JSON.stringify()提供有关格式化或美化输出的信息.

  • 如果你想要很好地格式化你也可以调用:`alert(JSON.stringify(object,null,4)`,其中`4`是用于缩进的空格数. (2认同)

Chr*_*ian 55

for- in环路,用于在一个物体或阵列中的每个属性.您可以使用此属性来获取值并更改它.

注意:私人财产不可用于检查,除非您使用"间谍"; 基本上,您覆盖对象并编写一些代码,这些代码在对象的上下文中执行for-in循环.

对于看起来像:

for (var property in object) loop();
Run Code Online (Sandbox Code Playgroud)

一些示例代码:

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));
Run Code Online (Sandbox Code Playgroud)

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

编辑2:好吧,无论如何我写了一个.

  • 这段代码彻底破坏了iPhone上的Safari Mobile。我会去下面的JSON.stringify解决方案,以获得更安全的选择。 (2认同)

Ran*_*eet 39

使用console.dir(object)和Firebug插件

  • 这给了我最完整和最有帮助的信息.谢谢. (4认同)
  • 我不知道`console.dir`功能.我无法理解为什么我再也无法在Firebug中查看完整的对象了.这已经为我排序了.谢谢! (2认同)

Ric*_*ato 17

使用您的控制台:

console.log(object);
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在检查html dom元素,请使用console.dir(object).例:

let element = document.getElementById('alertBoxContainer');
console.dir(element);
Run Code Online (Sandbox Code Playgroud)

或者如果你有一个js对象数组,你可以使用:

console.table(objectArr);
Run Code Online (Sandbox Code Playgroud)

如果要输出大量的console.log(对象),也可以编写

console.log({ objectName1 });
console.log({ objectName2 });
Run Code Online (Sandbox Code Playgroud)

这将帮助您标记写入控制台的对象.


小智 17

方法很少:

 1. typeof tells you which one of the 6 javascript types is the object. 
 2. instanceof tells you if the object is an instance of another object.
 3. List properties with for(var k in obj)
 4. Object.getOwnPropertyNames( anObjectToInspect ) 
 5. Object.getPrototypeOf( anObject )
 6. anObject.hasOwnProperty(aProperty) 
Run Code Online (Sandbox Code Playgroud)

在控制台上下文中,有时.constructor或.prototype可能有用:

console.log(anObject.constructor ); 
console.log(anObject.prototype ) ; 
Run Code Online (Sandbox Code Playgroud)


moe*_*moe 9

var str = "";
for(var k in obj)
    if (obj.hasOwnProperty(k)) //omit this test if you want to see built-in properties
        str += k + " = " + obj[k] + "\n";
alert(str);
Run Code Online (Sandbox Code Playgroud)


vaF*_*art 6

这是克里斯蒂安的出色回答的公然剽窃.我刚才让它更具可读性:

/**
 * 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
Run Code Online (Sandbox Code Playgroud)