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


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

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


Copy this code and paste it in your HTML
  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. };

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.