Skip to content

Instantly share code, notes, and snippets.

@sepehr
Created September 1, 2012 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sepehr/3563689 to your computer and use it in GitHub Desktop.
Save sepehr/3563689 to your computer and use it in GitHub Desktop.
JS: Dump Helper (print_r)
/**
* Debug helper similar to PHP's print_r().
*
* 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.
*
* @param data
* array, object or hash (assoc array)
* @param level
* Optional
*
* @return string
* The textual representation of the array.
*
* @see https://gist.github.com/3547657
*/
function print_r(arr, level) {
var dumped_text = '',
level_padding = '';
// Set default level
level || level = 0;
// The padding given at the beginning of the line.
for (var j=0; j < level + 1; j++) {
level_padding += ' ';
}
// Array/Hashes/Objects
if (typeof(arr) == 'object') {
for (var item in arr) {
var value = arr[item];
//If it is an array
if (typeof(value) == 'object') {
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value, level + 1);
}
else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
} // for
}
// Stings/Chars/Numbers etc.
else {
dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
}
return dumped_text;
}
@sepehr
Copy link
Author

sepehr commented Sep 1, 2012

It's a manual fork of https://gist.github.com/3547657

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment