Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a toString-like function for javascript objects?

While debugging and developing with javascript, I often wanted to alert the objects, so I used the below code:

for(a in obj)
{
  alert(a +' = '+obj[a])
}    

It serves well, but it is too annoying. I want to know if there is anything just like this for arrays:

var temp = ['a','b','c'];
alert(temp); // it will alert a,b,c 

So what I wish to do is:

var temp = {a:'a',b:'b',c:'c'};
alert(temp) ; // It should alert json {a:'a',b:'b',c:'c'}

Or any other better suggestion so I could look up the object easily.

like image 572
Rupesh Patel Avatar asked Jun 22 '26 03:06

Rupesh Patel


1 Answers

Alert calls toString, so you can overwrite toString for debugging purposes:

Object.prototype.toString = function() {
    return JSON.stringify(this);
};

So you can just call alert(foo); and it will display the JSON representation of foo

like image 51
Ortiga Avatar answered Jun 23 '26 17:06

Ortiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!