Javascript does not provide any direct implementation to print the contents of an array object. Such an implementation is very useful in debugging. Here is my version of the PHP’s print_r implementation:
/*
* Function to print an associative array/object/hash.
* @param Object a The collection to be printed
* @param String dTab This is used for indentation. Its recommended NOT to pass this variable in the function call.
* @return String ret The string representation of the collection.
* @author Kapil Chhabra
* @blog http://my-experiments-with-it.blogspot.com/
*/print_r = function(a, dTab) {
//initiate the return variable
var ret = “”;//the depth tabbing variable helps in indentation
if(!dTab) dTab = “\t”;//If the input variable is a collection object then iterate
if(typeof(a) == ‘object’){//foreach implementation in javascript
for(var sub in a) {
var val = a[sub];
ret += “‘” + sub + “‘ =>”;//incase the value obtained is again a collection
if(typeof(val) == ‘object’) {//drill it down by calling the print_r function recurrsively
ret += “\n” + dTab + “[" + print_r(val, dTab + "\t") + "]\n” + (dTab.substring(0, (dTab.length-1)));
} else {
ret += ” \”" + val + “\”";
}
}
} else {
//Not a collection
ret = “‘” + a + “‘ is of type ‘” + typeof(a) + “‘, not array/object.”;
}
return ret;
}
The usage is fairly simple.
var ar = [{0: [{'a': 'A'}, {'b': 'B'}]}, {1: 2}];
alert(print_r(ar));
alert(print_r(’x'));
It gives the following output:
This function has helped me a lot. Hope it helps others as well.













Did you consider using JSON? It is also human readable, but it’s native to javascript.