LoginSignup
338
327

More than 5 years have passed since last update.

JavaScriptでオブジェクトの型を判別するのにtypeof演算子使うとツラいよね

Last updated at Posted at 2013-05-10

何がツラいって一番ありがちな下記のような場合ですよね。

var a = {}, b = [], c = 'hoge', d = new String('hoge');

typeof a; // "object"
typeof b; // "object" ← ファッ?!
typeof c; // "string"
typeof d; // "object" ← ファッ?!

ObjectArray を区別してくれないとかないわー。new String()使うことないけど、区別しちゃうとかないわー。

ということで以前に自分が日本語訳したJavaScript Gardenにも書いてあった方法を使うと
判別が楽になるんじゃないかと。

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'hoge'); // true
is('String', new String('hoge')); // true

Object.prototype.toStringすることによって[[Class]]という内部プロパティを取得して必要なものを切り出してっていう話です。

これで下記のようなタイプを取得してこれますので比較対象として引数に渡してあげましょうという感じです。

  • String
  • Number
  • Boolean
  • Date
  • Error
  • Array
  • Function
  • RegExp
  • Object

これで大体感覚通りの型判別ができると思います。

余談ですが、上記のサイトの中で唯一typeofが使える場面としてた下記のような未定義変数の判別だけ!と書いてあります。

typeof hoge !== 'undefined'; // 未定義だとfalseに

ですよね…。

参照: http://bonsaiden.github.io/JavaScript-Garden/ja/#types.typeof

338
327
3

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
338
327