473,795 Members | 2,847 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

print_r(), JavaScript Edition

pbmods
5,821 Recognized Expert Expert
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.constru ctor.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, 327 views)
Aug 31 '07 #1
1 7155
Robert Kehoe
1 New Member
Awesome function, works great for me! :)

Just one question, what license can the code be used under? BSD, MIT, LGPL, etc... ?
Sep 14 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10448
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10217
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10167
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9046
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6784
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5566
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.