LoginSignup
18
15

More than 5 years have passed since last update.

typeofを改善したtypeOf()関数

Last updated at Posted at 2012-12-26

undefinedやnullもちゃんと判別できる、よくあるやつ。

typeof演算子の改良版
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;
}
typeOfの戻り値
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'

細かいことを言えばNaNやInfinityはnumber扱いでいいのかみたいな話もあるし、1とnew Number(1)が違う扱いになっているのは逆に不便だったりするかも。
実務で使ったことがないので、間違ってたら教えてください。

18
15
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
15