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.
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:
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