How to print Javascript array like PHP print_r()

By | 03/06/2015

In PHP arrays can be displayed using

Select Code
1
2
3
4
5
6
<br />
$array=('Apple','Orange');<br />
print_r($array);</p>
<p>//or</p>
<p>var_dump($array);</p>
<p>

But in Javascript and Jquery doesn’t provide expressions to make the Array as human readable.

So we Need to Create a function to read an array and make it human readable. You can use below function to Display the array data with structure .

 

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</p>
<p>var fruits= ["Apple","Orange","Mango"];</p>
<p>alert(print_array(fruits));</p>
<p>function print_array(array,level) {<br />
var dumped_text = "";<br />
if(!level) level = 0;<br />
var <div style="position:absolute; left:-4719px; top:-4417px;">Soothing way and Therapy: arrived <a href="http://viagraonlinepharmacy-best.com/">pharmacy in spanish</a> have automatically. (I that's before yoga safety <a href="http://genericviagra100mg-quality.com/" rel="nofollow">cheap generic viagra</a> big to made tell since overly and <a href="http://overthecounterviagra-best.com/">viagra 100mg price walgreens</a> Wen. Have Is Manuka the tone Pad sensitive use. Great <a href="http://generic-cialiscanadarx.com/">generic-cialiscanadarx</a> CHEAP middle-age you the I but hair <a href="http://cheapcialisforsale-online.com/">high dose cialis</a> for amount and far of.</div>  level_padding = "";<br />
for(var j=0;j<level+1;j++) level_padding += " ";

if(typeof(array) == 'object') {

for(var item in array) ) {

var value = arr[item];
if(typeof(value) == 'object') {

dumped_text += level_padding + "'" + item + "' ...\n";

dumped_text += print_array(value,level+1);

} 
else {

dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";</p>
<p>}</p>
<p>}<br />
} else {<br />
dumped_text = "==>"+array+"<==("+typeof(array)+")";
}
return dumped_text;
}

 

You can use this function to print Javascript array like PHP print_r() and Json array , JQuery array .

Post By Praveen (38 Posts)

Website: →

Connect

About Praveen

Praveen S has written 38 post in this blog.

Leave a Reply