A print_r function for Javascript (Recursively dumping arrays)

Binny V A over at Bin-Blog has written something marvellous: a print_r function for Javascript.

What does it do? It takes an array (or hash or object) and prints out every key with its value. If it comes along another array, it does the same thing again. It's such a useful feature in PHP, it's a great debugger-friend.

There are a few code snippets out there that do the same job, but I thought this one was quite small and compact.
Don't forget to wrap it in a <pre> tag to get a nice layout.


/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;
  
  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j \"" + value + "\"\n";
      }
    }
  } else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}

Jelle De Loecker
Written on vrijdag, 16 juli 2010 22:12 by Jelle De Loecker

Viewed 8513 times so far.
Like this? Tweet it to your followers!

Latest articles from Jelle De Loecker

blog comments powered by Disqus

Nederlands - nl-NLEngels
Over Kipdola Studios vzwKipdola is een vereniging zonder winst (opgericht eind 2009) die voornamelijk audiovisuele projecten op poten zet in het Pajottenland.
Contact Informatie
info@kipdola.be
www.kipdola.be
BTW: BE 0820952174
Locatie Oude Brusselsestraat 4
1750 Lennik
Vlaams-Brabant, België
De Kerngroep Jelle De Loecker
Kevin Van Campenhout
Lisenka Dekaezemaeker
Stéphanie Leroy