Connecting Tech Pros Worldwide Forums | Help | Site Map

print_r(), JavaScript Edition

pbmods's Avatar
Site Moderator
 
Join Date: Apr 2007
Location: Texas
Posts: 5,435
#1   Aug 31 '07
Looking for a print_r() for JavaScript? Look no further! Finally, a decent way to figure out what's in that mysterious Array or Object!

Note that this version of print_r() relies on (included) getType(), which is designed to be a browser-independent way of detecting basic types in JavaScript (unfortunately, the $object.constructor.match() trick doesn't work in Safari nor IE).

Special thanks to the following TSDN members whose help was invaluable and greatly appreciated during the development of this procedure:
  • gits
  • iam_clint
  • volectricity
  • Purple

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.     <head>
  3.         <script type="text/javascript">
  4. /**
  5. *   getType
  6. *
  7. *   Use this when typeof returns 'Object'.
  8. *
  9. *   @param mixed $obj The object to investigrate.
  10. *
  11. *   @return string The object's constructor.
  12. *
  13. *   @author Josh Zerin, Life Blue Media (http://www.lifeblue.com/)
  14. *   @author Special thanks to:
  15. *       - gits
  16. *       - iam_clint
  17. *       - volectricity
  18. *       - Purple
  19. *   http://www.thescripts.com/
  20. */
  21. function getType($obj)
  22. {
  23.     /***************
  24.     *
  25.     *   Two special cases:  undefined and null.
  26.     */
  27.     if( typeof $obj == 'undefined' )
  28.     {
  29.         return 'undefined';
  30.     }
  31.  
  32.     if($obj === null)
  33.     {
  34.         return 'null';
  35.     }
  36.  
  37.     /***************
  38.     *
  39.     *   Run through the standard constructors.
  40.     */
  41.     switch($obj.constructor)
  42.     {
  43.         case Array:
  44.             return 'Array';
  45.         case Boolean:
  46.             return 'Boolean';
  47.         case Date:
  48.             return 'Date';
  49.         case Error:
  50.             return 'Error';
  51.         case Function:
  52.             return 'Function';
  53.         case Number:
  54.             return 'Number';
  55.         case RegExp:
  56.             return 'RegExp';
  57.         case String:
  58.             return 'String';
  59.         default:
  60.  
  61.             /***************
  62.             *
  63.             *   HTML Elements will have a nodeType property.  It is unlikely, though possible, that other objects will.
  64.             */
  65.             if( typeof($obj.nodeType) != 'undefined' )
  66.             {
  67.                 return 'HTML ' + $obj.nodeName.toUpperCase() + ' Element';
  68.             }
  69.  
  70.             /***************
  71.             *
  72.             *   If it's not an HTML Element, it might be an Event.
  73.             */
  74.             if($obj.toString)
  75.             {
  76.                 if($obj.toString().match('Event'))
  77.                 {
  78.                     return 'Event';
  79.                 }
  80.             }
  81.  
  82.             /***************
  83.             *
  84.             *   I give up.
  85.             */
  86.             return 'Object';
  87.     }
  88. }
  89.  
  90. /**
  91. *
  92. *   print_r
  93. *
  94. *   Similar to the PHP function of the same name, except it always returns its output (I never liked that about PHP's print_r()).
  95. *
  96. *   @param mixed $content The variable you're trying to print_r.  Generally an object or array.
  97. *
  98. *   @param bool $htmlEncode How to format the output:
  99. *       - true:     Use <br /> for line breaks, and &nbsp; for tabs.
  100. *       - false:    Use \n for line breaks and \t for tabs.
  101. *
  102. *   @param string $basePrefix The base prefix that will be appended to all lines of output.  Very useful if you need your debug output to all line up (and something that REALLY bugs me about PHP's print_r()!).
  103. *
  104. *   @param string $_prefix (internal)
  105. *
  106. *   @return string A print_r()'ed string, similar in format to the PHP function of the same name (but with a few enhancements ~_^).
  107. *
  108. *   @author Josh Zerin, Life Blue Media (http://www.lifeblue.com/)
  109. *   @author Special thanks to:
  110. *       - gits
  111. *       - iam_clint
  112. *       - volectricity
  113. *       - Purple
  114. *   http://www.thescripts.com/
  115. */
  116. function print_r($content, $htmlEncode, $basePrefix, $_prefix)
  117. {
  118.     /***************
  119.     *
  120.     *   $_prefix must be a string.
  121.     */
  122.     if( ! $_prefix )
  123.     {
  124.         $_prefix = '';
  125.     }
  126.  
  127.     /***************
  128.     *
  129.     *   Set the $basePrefix if not already set.
  130.     */
  131.     if( ! $basePrefix )
  132.     {
  133.         $basePrefix =
  134.         (
  135.             // If $_prefix is defined, we'll just use that.
  136.             $_prefix
  137.                 ? $_prefix
  138.                 :
  139.                 (
  140.                     // Otherwise, use a default.
  141.                     $htmlEncode
  142.                         ? '&nbsp;&nbsp;&nbsp;&nbsp;'
  143.                         : '\t'
  144.                 )
  145.         );
  146.     }
  147.  
  148.     /***************
  149.     *
  150.     *   How do we display newlines?
  151.     */
  152.     var $newLine = ($htmlEncode ? '<br />' : '') + '\n';
  153.  
  154.     /***************
  155.     *
  156.     *   Init output string.
  157.     */
  158.     var $retVal = '';
  159.  
  160.     /****************
  161.     *
  162.     *   We don't need to redundantly output certain types (the 'value' of null & undefined are self-explanatory, and we auto-output the type of Array & Object, so we don't want to do it twice).
  163.     */
  164.     var $blacklistDisplayType =
  165.     {
  166.         'null':         true,
  167.         'Array':        true,
  168.         'Object':       true,
  169.         'undefined':    true
  170.     }
  171.  
  172.     /***************
  173.     *
  174.     *   Begin processing $content.
  175.     */
  176.     var $myType = getType($content);
  177.     var $subType = '';
  178.  
  179.     /***************
  180.     *
  181.     *   And off we go!
  182.     */
  183.     if( $myType == 'Array' )
  184.     {
  185.         // E.g., "Array:\n\t(\n"
  186.         $retVal += $myType + ':' + $newLine + $_prefix + '(' + $newLine;
  187.  
  188.         /***************
  189.         *
  190.         *   Save the closing format before we go modifying $_prefix.
  191.         */
  192.         var $close = $_prefix + ')' + $newLine;
  193.  
  194.         /***************
  195.         *
  196.         *   $basePrefix is only for *child* elements of the array.
  197.         */
  198.         $_prefix += $basePrefix;
  199.  
  200.         /***************
  201.         *
  202.         *   for...in not useful on Arrays, since that will also return member functions.
  203.         */
  204.         for( var $i = 0; $i < $content.length; ++$i )
  205.         {
  206.             var $innerType = getType($content[$i]);
  207.  
  208.             // E.g., "\t\t0 => (Number) "
  209.             $retVal += $_prefix + $i + ' => ' +
  210.             (
  211.                 /***************
  212.                 *
  213.                 *   Should we display the type of the child element?
  214.                 */
  215.                 $blacklistDisplayType[$innerType]
  216.                     ? ''
  217.                     : ' (' + getType($content[$i]) + ')'
  218.             ) + ' ';
  219.  
  220.             /***************
  221.             *
  222.             *   If the child element has children of its own, recursively process them.
  223.             */
  224.             if(($innerType == 'Array') || ($innerType == 'Object'))
  225.             {
  226.                 $retVal +=
  227.                     print_r
  228.                     (
  229.                         $content[$i],
  230.                         $htmlEncode,
  231.                         $basePrefix,
  232.                         $_prefix
  233.                     );
  234.             }
  235.             else
  236.             {
  237.                 $retVal += $content[$i] + $newLine;
  238.             }
  239.         }
  240.  
  241.         // E.g., "\t)\n"
  242.         $retVal += $close;
  243.     }
  244.     else if( $myType == 'Object' )
  245.     {
  246.         $retVal += $myType + ':' + $newLine + $_prefix + '(' + $newLine;
  247.         var $close = $_prefix + ')' + $newLine;
  248.         $_prefix += $basePrefix;
  249.  
  250.         /***************
  251.         *
  252.         *   for not useful on Objects, since they generally have no length property.
  253.         */
  254.         for( $i in $content )
  255.         {
  256.             var $innerType = getType($content[$i]);
  257.             $retVal += $_prefix + $i + ' => ' +
  258.             (
  259.                 $blacklistDisplayType[$innerType]
  260.                     ? ''
  261.                     : ' (' + getType($content[$i]) + ')'
  262.             ) + ' ';
  263.  
  264.             if( ($innerType == 'Array') || ($innerType == 'Object') )
  265.             {
  266.                 $retVal +=
  267.                     print_r
  268.                     (
  269.                         $content[$i],
  270.                         $htmlEncode,
  271.                         $basePrefix,
  272.                         $_prefix
  273.                     );
  274.             }
  275.             else
  276.             {
  277.                 $retVal += $content[$i] + $newLine;
  278.             }
  279.         }
  280.  
  281.         $retVal += $close;
  282.     }
  283.     else
  284.     {
  285.         /***************
  286.         *
  287.         *   If it ain't an object, then it's scalar.
  288.         */
  289.         $retVal += $content;
  290.     }
  291.  
  292.     /***************
  293.     *
  294.     *   And we're done!
  295.     */
  296.     return $retVal;
  297. }
  298.         </script>
  299.     </head>
  300.  
  301.     <body>
  302.         <script type="text/javascript">
  303.         // <![CDATA[
  304.  
  305.             /*
  306.                 Desired output:
  307.  
  308.                 Object:
  309.                 (
  310.                     Array => Array:
  311.                     (
  312.                         0 => (Number) 0
  313.                         1 => (String) 1
  314.                         2 => (Number) 2.3
  315.                         3 => (String) Four
  316.                         4 => Object:
  317.                         (
  318.                             Five => (Number) 5
  319.                         )
  320.                     )
  321.                     Number => (Number) 1
  322.                     Float => (Number) 2.3
  323.                     String => (String) Four
  324.                     Sub => Object:
  325.                     (
  326.                         empty => (Boolean) false
  327.                     )
  328.                     null => null
  329.                     undef => undefined
  330.                     Element => (HTML BODY Element) [object HTMLBodyElement]
  331.                 )
  332.             */
  333.  
  334.             var $theObj = {
  335.                 'Array':    [
  336.                     0, '1', 2.3, 'Four', { 'Five': 5 }
  337.                 ],
  338.                 'Number':   1,
  339.                 'Float':    2.3,
  340.                 'String':   'Four',
  341.                 'Sub':      {
  342.                     'empty':    false
  343.                 },
  344.                 'null':     null,
  345.                 'undef':    undefined,
  346.                 'Element':  document.getElementsByTagName('body')[0]
  347.             };
  348.  
  349.             document.write(print_r($theObj, true));
  350.         // ]]>
  351.         </script>
  352.     </body>
  353. </html>
  354.  
Attached Files
File Type: zip print_r.html.zip (2.8 KB, 138 views)



Reply