Recursive Object Traversal in Javascript (like PHP’s print_r…)
I’ve been banging my head against the wall for the past few weeks trying to debug Javascript issues in Internet Explorer. (I can hear you cringing already…) At least, with the advent of IE8, there is now an official script debugger included in the new Developer Tools. Unfortunately, it is severely lacking when compared to the debugging capabilities of Firefox with the Firebug plugin — and debugging with Firebug doesn’t guarantee that the script will work in any version of IE.
I use the following function, based on a script by Matt Hackett, in the console window of the IE8 Developer Tools to quickly inspect any object currently in scope in the script I’m debugging. I have this function declared in a Javascript file that I include into all of my pages while I’m developing them. The arguments are fairly straightforward:
xis the object being inspectedmaxis maximum depth of recursion into the object structuresMaxis the maximum display length for String propertiesskipMethodsskips displaying object properties that are functions (methods in OOP)sepis the string value used to indent the levels of recursion in the displaylis the level of recursion for the current function call
All of the arguments, with the exception of x, have reasonable defaults. You can see the default values in the first five lines of the function. Here is the code:
function print_r(x, max, sMax, skipMethods, sep, l) {
max = max || 10;
sMax = sMax || 25;
skipMethods = skipMethods || true;
sep = sep || ' ';
l = l || 0;
if (l > max) return "[Stopped at " + l + " levels]\n";
var i, r = '', t = typeof x, tab = '';
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 + ':' + l + ") :\n";
for (i in x) {
if (!(typeof x[i] == 'function' && skipMethods)) {
try {
r += tab + '[' + i + '] : ' +
print_r(x[i], max, sMax, skipMethods, sep, l);
}
catch (e) {
return "[ERROR: " + e + "]\n";
}
}
}
}
else {
var sLen = '';
if (t == 'string') {
sLen = '[' + x.length + ']';
if (x.length > sMax)
x = x.substr(0, sMax) + '...';
}
if (!(t == 'function' && skipMethods)) {
r += '(' + t + sLen + ') ' + x + "\n";
}
}
return r;
}
This function prints all of the properties and, optionally, methods of the object passed as the x argument recursively to a depth of the max argument. It makes it quick and painless to inspect values while debugging. It also labels each level of recursion and shows the length of String properties, which is handy when they’ve been truncated by the sMax argument.
Hopefully, someone will find this useful. A text version of the source is available here.
Filed in Javascript, Technology No Responses yet