Javascript - Debugging Javascript as PHP / Function var_dump


/ Published in: JavaScript
Save to your folder(s)

In javascript there is no function for printing variables like you have PHP, I use print_r and var_dump a lot in PHP for dumping variables
so I wanted to create a simular function in javascript.


Copy this code and paste it in your HTML
  1. function var_dump( objElement, intLimit, intDepth )
  2. {
  3. intDepth = intDepth?intDepth:0;
  4. intLimit = intLimit?intLimit:1;
  5.  
  6. strReturn = '<ol>';
  7.  
  8. for( property in objElement )
  9. {
  10. // Property domConfig isn't accesible
  11. if( property != 'domConfig' )
  12. {
  13. strReturn += '<li><strong>' + property + '</strong> <small>(' + ( typeof objElement[property] ) + ')</small>';
  14.  
  15. if ( typeof objElement[property] == 'number' || typeof objElement[property] == 'boolean' ) {
  16. strReturn += ' : <em>' + objElement[property] + '</em>';
  17. }
  18.  
  19. if ( typeof objElement[property] == 'string' && objElement[property] ) {
  20. strReturn += ': <div style="background:#C9C9C9; border:1px solid black; overflow:auto;"><code>' +
  21. objElement[property].replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</code></div>';
  22. }
  23.  
  24. if ( typeof objElement[property] == 'object' && ( intDepth < intLimit ) ) {
  25. strReturn += var_dump( objElement[property], intLimit, ( intDepth + 1 ) );
  26. }
  27.  
  28. strReturn += '</li>';
  29. }
  30. }
  31.  
  32. strReturn += '</ol>';
  33.  
  34. if ( intDepth == 0 )
  35. {
  36. winpop = window.open( "", "", "width=800, height=600, scrollbars, resizable" );
  37. winpop.document.write( '<pre>' + strReturn + '</pre>' );
  38. winpop.document.close();
  39. }
  40.  
  41. return strReturn;
  42. }

URL: http://remorse.nl/2008/07/javascript_debugging_print_rvar_dump_in_javascript_like_php/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.