Posted By

rolandog on 01/17/07


Tagged

object type array of typeof identification null undefined boolean


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

rolandog
markireland
korzhik
wizard04
lex_machina
guo3823538


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  

Comments

RSS Icon Subscribe to comments
Posted By: jameswatts on August 3, 2009

var type = { of: function(obj) { var type = typeof(obj); if(type == 'object') { if(obj == null) { return 'null'; } else if(obj.constructor.toString().match(/regexp/i) != null) { return 'regexp'; } else if(obj.constructor.toString().match(/date/i) != null) { return 'date'; } else if(obj.constructor.toString().match(/html/i) != null) { return 'html'; } else if(obj.constructor.toString().match(/array/i) != null && typeof(obj.length) != 'undefined') { return 'array'; } else { return 'object'; } } else { return type; } } };

Posted By: CDRates on February 8, 2010

Great bit of code!

You need to login to post a comment.