Last active
August 29, 2015 13:55
-
-
Save hirak/8782812 to your computer and use it in GitHub Desktop.
typeofを改善したtypeOf()関数 ref: http://qiita.com/Hiraku/items/87e5d1cdaaa475c80cc2
This file contains hidden or 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
console.log(typeOf(undefined)); //'undefined' | |
console.log(typeOf(null)); //'null' | |
console.log(typeOf("str")); //'string' | |
console.log(typeOf(new String("str"))); //'String' | |
console.log(typeOf(true)); //'boolean' | |
console.log(typeOf(new Boolean(true))); //'Boolean' | |
console.log(typeOf(1)); //'number' | |
console.log(typeOf(NaN)); //'NaN' | |
console.log(typeOf(Infinity)); //'Infinity' | |
console.log(typeOf(-Infinity)); //'-Infinity' | |
console.log(typeOf(new Number(1))); //'Number' | |
console.log(typeOf(function(){})); //'function' | |
console.log(typeOf([])); //'Array' | |
console.log(typeOf(/aaa/)); //'RegExp' | |
console.log(typeOf(new Date)); //'Date' | |
console.log(typeOf(document)); //'Document' | |
console.log(typeOf({})); //'Object' | |
console.log(typeOf(Object.create(null))); //'Object' | |
console.log(typeOf(new function Hoge(){})); //'Hoge' IEでは'Object' |
This file contains hidden or 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
function typeOf(x) { | |
if (x === null) return 'null'; | |
if (x == null) return 'undefined'; | |
var type = typeof x, c = x.constructor; | |
if (type === 'number') { | |
if (isNaN(x)) return 'NaN'; | |
if (!isFinite(x)) | |
return x === Infinity ? 'Infinity' : '-Infinity'; | |
} | |
if (type === 'object') { | |
return c && c.name ? c.name : | |
Object.prototype.toString.call(x).slice(8, -1); | |
} | |
return type; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment