如何检查 Javascript 对象

如何检查通知框中的 Object? 通常通知 Object 只会抛出节点名:

alert(document);

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

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

108325 次浏览
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);

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.

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.

Use console.dir(object) and the Firebug plugin

Use your console:

console.log(object);

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

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

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

console.table(objectArr);

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

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

This will help you label the objects written to console.

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:

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

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

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

Use like this :

document.write(inspect(object));