A print_r function for Javascript (Recursively dumping arrays)

By on

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;
}

Comments

Name
Email
Website
Body
Jelle De Loecker