As shown in lines 1017 of Listing 7-4, there are lots of cases in JavaScript in which you have an object but don't know what properties it contains. This is especially common when you are passing JSON-encoded data from the server to the client. JavaScript provides the "for in" loop for looping over the properties of any object. Using this loop, you can construct a basic dump function that allows you to quickly see the properties of an object. Listing 7-7 shows an example function.
A JavaScript Property Dumping Functionfunction dump(input) {
var msg = '';
for(var i in input) {
msg += i+':'+input[i]+"\n";
}
return msg;
}
You can then use this function to alert the contents of the object or assign the debug output to a debug element on a page. A simple function like this can save a great deal of time in the debugging and development processes. Building on this same concept, the HTML AJAX library provides a utility function called varDump that provides additional information. This method is based on the var_dump function in PHP and provides the type of each element as well as its value. It also supports recursion, giving you the output of any child objects. Listings 7-8 and 7-9 show the output of varDump against different inputs. Sample usage is shown in the following code:
alert(HTML_AJAX_Util.varDump(input));
Sample varDump Output (an Array with Another Nested Inside It)array(3) {
[0]=>
number(1)
[1]=>
array(3) {
[0]=>
number(1)
[1]=>
number(2)
[2]=>
number(3)
}
[2]=>
number(3)
}
Sample varDump Output (an Object)object(Object) (2) {
["bar"]=>
string(3) "baz"
["bat"]=>
number(5)
}
Monday, September 17, 2007
Dumping Variables
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment