How to inspect Javascript Objects
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 method开发者_运维技巧s 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.
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.
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.
Use console.dir(object)
and the Firebug plugin
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 ) ;
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.
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);
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));
精彩评论