How do I read a Javascript Object when I don't know what's in it?
I've been wo开发者_运维百科rking on node.js and have a variable for which I really don't know what's in it. When I try sys.puts:
sys.puts(headers) // returns [object Object]
If there was something like a print_r in javascript, that would have been fine.
You can loop over its properties with
for (var item in headers)
{
// item is the name of the property
// headers[item] is the value
}
example at http://www.jsfiddle.net/gaby/CVJry/3/ (requires console)
If you want to limit the results to direct properties (not inherited through the prototype chain) then use as well the hasOwnProperty
method.
example at http://www.jsfiddle.net/gaby/CVJry/2/
Most web browsers can use the JSON-object to print the contents of an object,
writeln(JSON.stringify(your_object));
If that fails, you can create your own stringifier;
var stringify = function(current) {
if (typeof current != 'object')
return current;
var contents = '{';
for (property in current) {
contents += property + ": " + stringify(current[property]) + ", ";
}
return contents.substring(0, contents.length - 2) + "}";
}
var my_object = {my_string: 'One', another_object: {extra: 'Two'}};
writeln(stringify(my_object));
You can loop through your object to know its properties & their values
Suppose your object is
var emp = {
name:'abc',
age:12,
designation:'A'
}
Now you can read its details in JS
for(property in emp ){
alert(emp[property] + " " +property);
}
If you have firebug in added in your Firefox browser, open it & write either in JS or JS window in Firebug console.
console.log(a);
If you need it just to check what's in an object (ie, it's relevant to you for some reason, but you don't need that functionality in your script), you can just use Firebug to get the object and check exactly what's in it.
精彩评论