tags:

views:

67

answers:

6

Is there any method or way to check what is inside a JavaScript object. something like print_r in PHP?

Cheers

+5  A: 

Use Firebug for Firefox or Developer Tools for Google Chrome/Safari to inspect your objects. It's the best way to do it in my opinion.

floatless
+1 To the point
naikus
A: 

Consider the following object:

var x = {
  property1: 'value1',
  property2: 'value2',
  property3: 'value3',
  method1: function () {
    return 0;
  },
  method2: function () {
    return 0;
  }
};

Then doing:

for (var prop in x) {
  console.log(prop);
}

Outputs:

property1
property2
property3
method1
method2

You may want to use the hasOwnProperty() method to ensure that you do not get properties from the object's prototype chain:

for (var prop in x) {
  if (x.hasOwnProperty(prop)) {
    console.log(prop);
  }
}
Daniel Vassallo
+1  A: 

Use this custom function or JSON.stringify(obj);

  /**
   * Gets the string representation of the specified object. This method is
   * used for debugging
   * @param {Object} Object to convert to string
   * @return {String} The string representation of the object
   */
  var toObjectSource = function(obj)   {
     if(obj === null)   {
        return "[null]";
     }
     if(obj === undefined) {
        return "[undefined]";
     }

     var str = "[";
     var member = null;
     for(var each in obj)   {
        try   {
           member = obj[each];
           str += each + "=" + member + ", ";
        }catch(err) {
           alert(err);
        }
     }
     return str + "]";
  }
naikus
A: 

Javascript objects are esentially maps of key/value pairs. You can access members through both dot notation (e.g. myObject.someProp), or even through index notation (myObject["someProp"]). The use of the latter will probably help you:

function print(obj) {
    for (var i in obj)
        console.log(i + " - " + obj[i]);
    }
}

Run that through Firebug and see what you get :)

Matthew Abbott
A: 

Install FireBug. Its a plug-in for Mozilla Firefox.

In your source file, write: console.log(yourObjectGoesHere); and go to the "console" tab in FireBug... Killer object discovery, presented in an easy-to-grasp tree-format.

roosteronacid
+2  A: 

If you use Mozilla Firefox, you can use Firebug. To see what your variable or object is, do it like code below (for example, I use JSON variable)

var yourObject = {test: 'this is just a test'};
console.log(yourObject); 

After you install Firebug, run your html file that contains this javascript and choose Console tab in Firebug. You will see the result there. Hope this helps you. :)

bhoo-day