Created
May 17, 2013 15:59
-
-
Save TJkrusinski/5600070 to your computer and use it in GitHub Desktop.
Type checker for JS that actually works.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Taken from http://james.padolsey.com/javascript/checking-types-in-javascript/ | |
*/ | |
function type(o){ | |
return !!o && Object.prototype.toString.call(o).match(/(\w+)\]/)[1]; | |
} | |
type(101); // returns 'Number' | |
type('hello'); // returns 'String' | |
type({}); // returns 'Object' | |
type([]); // returns 'Array' | |
type(function(){}); // returns 'Function' | |
type(new Date()); // returns 'Date' | |
type(document); // returns 'HTMLDocument' | |
// For example, to test for an Array: | |
if( type([1,2,3,4,5]) === 'Array' ) doStuff(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment