Javascript Dump Function

This section contains a lot of Scripting material for your website.

Javascript Dump Function

Postby Web Guru on July 27th, 2008, 5:53 am

If you are a PHP develoepr you might have come across the print_r() or var_dump() functions, they are very usefull to see the contents of an array or object. Here is an equivalent function in javascript to perform the same task.

Code: Select all
/**
*
* Function : dump( )
* Arguments: The data - array,hash(associative array),object
*            The level - OPTIONAL
*
**/

function dump(arr,level)
{
   var dumped_text = "";
   
   if (!level)
      level = 0;

   //The padding given at the beginning of the line.
   var level_padding = "";
   
   for(var j = 0; j < (level + 1); j ++)
      level_padding += "    ";

   if (typeof(arr) == 'object')
   {
      //Array/Hashes/Objects
      
      for(var item in arr)
      {
         var value = arr[item];

         if(typeof(value) == 'object')
         {
            //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += dump(value,level+1);
         }
         
         else
         {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
         }
      }
   }
   
   else
   {
      //Stings/Chars/Numbers etc.
      dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
   }
   
   return dumped_text;
}
User avatar
Web Guru
 
Posts: 66
Joined: March 24th, 2008, 7:59 am
Location: Lahore, Pakistan

Return to Java Script / VB Script

Who is online

Users browsing this forum: No registered users and 0 guests

cron