문제

How do I read a Javascript Object when I don't know what's in it?

I've been working 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.

도움이 되었습니까?

해결책

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 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/

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top