Monday, September 13, 2010

JavaScript print_r() or var_dump() Equivalent

SkyHi @ Monday, September 13, 2010
/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_jc(x, max, sep, l) {

 l = l || 0;
 max = max || 10;
 sep = sep || ' ';

 if (l > max) {
  return "[WARNING: Too much recursion]\n";
 }

 var
  i,
  r = '',
  t = typeof x,
  tab = '\t';

 if (x === null) {
  r += "(null)\n";
 } else if (t == 'object') {

  l++;

  for (i = 0; i < l; i++) {
   tab += sep;
  }

  if (x && x.length) {
   t = 'Array';
  }

  r += '(' + t + ") \n";
  r += '('+"\n";


  for (i in x) {
   try {
    r += tab + '[' + i + '] => ' + print_jc(x[i], max, sep, (l + 1));
   } catch(e) {
    return "[ERROR: " + e + "]\n";
   }
  }
  r += ')';


 } else {

  if (t == 'string') {
   if (x == '') {
    x = '(empty)';
   }
  }

  r += '(' + t + ') ' + x + "\n";

 }

 return r;

}




TEST:
//var colors = new Array("red", "blue", "green");
var colors = ["red", "blue", "green"];
document.write('
');
document.write(print_jc(colors));
document.write('
');


Output:
(Array) 
(
  [0] => (string) red
  [1] => (string) blue
  [2] => (string) green
)



REFERENCES
http://scriptnode.com/article/javascript-print_r-or-var_dump-equivalent/