Section 7.5. Dumping Variables


7.5. Dumping Variables

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.

Listing 7-7. A JavaScript Property Dumping Function

function 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));


Listing 7-8. 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) }

Listing 7-9. Sample varDump Output (an Object)

object(Object) (2) {   ["bar"]=>   string(3) "baz"   ["bat"]=>   number(5) }




Understanding AJAX(c) Using JavaScript to Create Rich Internet Applications
Understanding AJAX: Using JavaScript to Create Rich Internet Applications
ISBN: 0132216353
EAN: 2147483647
Year: N/A
Pages: 154

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net