Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Forked from faisalman/print_r.js
Last active August 29, 2015 14:23
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 barseghyanartur/64366127ad0eef400f5e to your computer and use it in GitHub Desktop.
Save barseghyanartur/64366127ad0eef400f5e to your computer and use it in GitHub Desktop.
Usage example
==============
-- Consider there is an object:
var obj = { foo: 'foo', bar: { foo: true, bar: null, baz: function(){alert('Hello');}}, qux: [1, 3, 2, 'qwerty', 55], quxx: /^[0-9]/ };
-- Then print_r(obj) or var_dump(obj) will return:
Object
{
foo => 'foo',
bar => Object
{
foo => true,
bar => null,
baz => function (){alert('Hello');}
},
qux => Array
[
0 => 1,
1 => 3,
2 => 2,
3 => 'qwerty',
4 => 55
],
quxx => /^[0-9]/
}
/**
* PHP-like print_r() equivalent for JavaScript Object
*
* @author Faisalman <fyzlman@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php
* @link http://gist.github.com/879208
*/
var print_r = function (obj, t) {
// define tab spacing
var tab = t || '';
// check if it's array
var isArr = Object.prototype.toString.call(obj) === '[object Array]';
// use {} for object, [] for array
var str = isArr ? ('Array\n' + tab + '[\n') : ('Object\n' + tab + '{\n');
// walk through it's properties
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var val1 = obj[prop];
var val2 = '';
var type = Object.prototype.toString.call(val1);
switch (type) {
// recursive if object/array
case '[object Array]':
case '[object Object]':
val2 = print_r(val1, (tab + '\t'));
break;
case '[object String]':
val2 = '\'' + val1 + '\'';
break;
default:
val2 = val1;
}
str += tab + '\t' + prop + ' => ' + val2 + ',\n';
}
}
// remove extra comma for last property
str = str.substring(0, str.length - 2) + '\n' + tab;
return isArr ? (str + ']') : (str + '}');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment