Home » jQuery

jQuery: Print array and object

22 January 2010 3,610 views No Comment Popularity: 37% Share/Bookmark

It’s very easy to print array and object with jQuery. You can do it with jQuery.each() function. The jQuery.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array.

Here is the javascript code to print array or object:

jQuery(document).ready(function(){
	var arr = [ "earth", "mars", "jupiter", "saturn", "venus" ];
	var obj = { one:"earth", two:"mars", three:"jupiter", four:"saturn", five:"venus" };

	jQuery.each(arr, function(i, val) {
	  $("#arrData").append(i + " : " + val + "<br/>");
	});

	jQuery.each(obj, function(i, val) {
	  $("#objData").append(i + " => " + val + "<br/>");
	});
});

Here, arr is a numeric array. Its key and value are printed in the div with id arrData. Similarly, obj is an associative array or object. Its key and value are printed in the div with id objData.

Here is the full source code:

<html>
<head>
<title>jQuery: Print array and object</title>
<script src="jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
	jQuery(document).ready(function(){
		var arr = [ "earth", "mars", "jupiter", "saturn", "venus" ];
		var obj = { one:"earth", two:"mars", three:"jupiter", four:"saturn", five:"venus" };

		jQuery.each(arr, function(i, val) {
		  $("#arrData").append(i + " : " + val + "<br/>");
		});

		jQuery.each(obj, function(i, val) {
		  $("#objData").append(i + " => " + val + "<br/>");
		});
	});
</script>
</head>
<body>
<div id="arrData">
<strong>Array</strong><br/>

</div>

<div id="objData">
<strong>Object</strong><br/>

</div>
</body>
</html>

Cheers,

From Mukesh Chapagain's Blog | Post jQuery: Print array and object

Related posts:

  1. print_r in Javascript
  2. jQuery: Preview Image with Tooltip Effect
  3. jQuery: Preview Image with Zoom Effect
  4. jQuery: Grey out background and preview image as popup
  5. jQuery: A simple Slideshow

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.