We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

rolandog on 01/17/07


Tagged

object type array of typeof identification null undefined boolean


Versions (?)


Who likes this?

5 people have marked this snippet as a favorite

rolandog
markireland
korzhik
wizard04
lex_machina


type.of() - a more specific typeof()


Published in: JavaScript 


URL: http://rolandog.com/archives/2007/01/18/typeof-a-more-specific-typeof/

Helps identify correctly the type of whatever you put as an argument. This was adapted from http://www.planetpdf.com/developer/article.asp?ContentID=testingforobjecttypesin_ja

  1. var is={
  2. Null:function(a){
  3. return a===null;
  4. },
  5. Undefined:function(a){
  6. return a===undefined;
  7. },
  8. nt:function(a){
  9. return(a===null||a===undefined);
  10. },
  11. Function:function(a){
  12. return(typeof(a)==='function')?a.constructor.toString().match(/Function/)!==null:false;
  13. },
  14. String:function(a){
  15. return(typeof(a)==='string')?true:(typeof(a)==='object')?a.constructor.toString().match(/string/i)!==null:false;
  16. },
  17. Array:function(a){
  18. return(typeof(a)==='object')?a.constructor.toString().match(/array/i)!==null||a.length!==undefined:false;
  19. },
  20. Boolean:function(a){
  21. return(typeof(a)==='boolean')?true:(typeof(a)==='object')?a.constructor.toString().match(/boolean/i)!==null:false;
  22. },
  23. Date:function(a){
  24. return(typeof(a)==='date')?true:(typeof(a)==='object')?a.constructor.toString().match(/date/i)!==null:false;
  25. },
  26. HTML:function(a){
  27. return(typeof(a)==='object')?a.constructor.toString().match(/html/i)!==null:false;
  28. },
  29. Number:function(a){
  30. return(typeof(a)==='number')?true:(typeof(a)==='object')?a.constructor.toString().match(/Number/)!==null:false;
  31. },
  32. Object:function(a){
  33. return(typeof(a)==='object')?a.constructor.toString().match(/object/i)!==null:false;
  34. },
  35. RegExp:function(a){
  36. return(typeof(a)==='function')?a.constructor.toString().match(/regexp/i)!==null:false;
  37. }
  38. };
  39.  
  40. var type={
  41. of:function(a){
  42. for(var i in is){
  43. if(is[i](a)){
  44. return i.toLowerCase();
  45. }
  46. }
  47. }
  48. };

Report this snippet 

You need to login to post a comment.