如何检查 Javascript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5357442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:50:44  来源:igfitidea点击:

How to inspect Javascript Objects

javascriptobjectinspect

提问by Valentina

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?

但是我想在警报框中获取对象的属性和方法。如果可能,我怎样才能实现这个功能?或者还有其他建议吗?

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

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

采纳答案by Christian

The for-inloops 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-in 循环。

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.

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

回答by Torsten Becker

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

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

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?

对于TypeError: Converting circular structure to JSON,这里有更多选项:即使存在循环引用,如何将 DOM 节点序列化为 JSON?

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

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

回答by Ranjeet

Use console.dir(object)and the Firebug plugin

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

回答by Richard Torcato

Use your console:

使用您的控制台:

console.log(object);

Or if you are inspecting html dom elements use console.dir(object). Example:

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

let element = document.getElementById('alertBoxContainer');
console.dir(element);

Or if you have an array of js objects you could use:

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

console.table(objectArr);

If you are outputting a lot of console.log(objects) you can also write

如果你输出很多 console.log(objects) 你也可以写

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

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

回答by brotherol

There are few methods :

有几种方法:

 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) 

In a console context, sometimes the .constructor or .prototype maybe useful:

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

console.log(anObject.constructor ); 
console.log(anObject.prototype ) ; 

回答by moe

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

回答by vaFyreHeart

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

回答by Muhammad Eko Avianto

Here is my object inspector that is more readable. Because the code takes to long to write down here you can download it at http://etto-aa-js.googlecode.com/svn/trunk/inspector.js

这是我的对象检查器,它更具可读性。因为这里的代码需要很长时间才能写下来,你可以在http://etto-aa-js.googlecode.com/svn/trunk/inspector.js下载它

Use like this :

像这样使用:

document.write(inspect(object));