Blogs Jelle's blog 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 4976 times so far.
Like this? Tweet it to your followers!

Latest articles from Jelle De Loecker

Latest 'tweets' from Jelle De Loecker

  • The series finale :( http://t.co/vxgvuyxH @GetGlue @HOUSEonFOX Link dinsdag, 22 mei 2012 13:45
  • @tmdpw Welke rivier? Ik ga alvast de generische naam "de waterwegmoord" opeisen. Link dinsdag, 22 mei 2012 13:23
  • @freeman2501 Het is uiteindelijk gelukt! Had toch direct voor de CD oplossing moeten gaan ;) Link dinsdag, 22 mei 2012 13:16
blog comments powered by Disqus

Bekijk onze kortfilm "Zin"

Scroll To Top