Skip to content

Instantly share code, notes, and snippets.

@hirak
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirak/8782812 to your computer and use it in GitHub Desktop.
Save hirak/8782812 to your computer and use it in GitHub Desktop.
typeofを改善したtypeOf()関数 ref: http://qiita.com/Hiraku/items/87e5d1cdaaa475c80cc2
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'
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