tags:

views:

9638

answers:

6

i want print the content of a javascript object in a string format like when we alert a variable in javascript same way i want print the object in formatted way

+14  A: 

Well, Firefox and other advanced browsers have Object.toSource() method which prints objects as JSON and function(){}.

That's enough for most debugging purposes, I guess.

alamar
+8  A: 

If you want to print the object for debugging purposes, I suggest instead installing Firebug for Firefox and using the code:

console.log(obj)
Triptych
That function also works on Google Chrome when using the JavaScript Console (Shift+Control+J or Shift+Control+I, depending on the Chrome version). Also note that `console.log(obj1, obj2)` works very nicely, too, so you don't have to call `console.log()` for every object when logging multiple variables. Also, always remember to remove all such calls in production, as it will break browsers that do not implement it (such as Internet Explorer).
Felix
+5  A: 
var output = '';
for (property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);
Flavius Stef
I was looking for a php style `foreach()` thanks!
DavidYell
A: 

RE: Triptych

If you want to print the object for debugging purposes, I suggest instead installing Firebug for Firefox and using the code:

console.log(obj)

Remember to enable the Console tab in Firebug.

Mike Chelen
A: 

Doesn't help when the object appears fine in FF and not so much in IE8. What are some options for dumping an object's contents while running it in IE8?

cindy
Hi Cindy, welcome to SO! This question of yours should be a comment to one of the answers or the question, rather than here in the 'answer' section. Or, post it as a separate question.
Alex JL
A: 

If you want to use alert, to print your object, you can do this:

alert("myObject is " + myObject.toSource());

It should print each property and its corresponding value in string format.

Garry