jQuery: Print array and object
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,
Related posts:
- Magento jQuery: How to use them together?
- PHP Javascript : Playing with multi-dimensional array
- jQuery: How to replace string, div content and image src?
- jQuery: A simple Tooltip
- jQuery: A simple Slideshow
- print_r in Javascript
- Using jQuery & AJAX: Populate Selection List
- jQuery: Set time interval between events with queue function
- PHP: Parse Unparse String Array
- Simple and easy jQuery tabs with AJAX and PHP
