20
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript つい忘れてしまう、配列かオブジェクトかの判定方法

Posted at

これも忘れちゃうんですよね。

#Object.prototype.toString.callの結果で判定する
これがシンプルでよいかなと思います。


if(Object.prototype.toString.call(a) === '[object Array]')

なお、他の値でやってみるとこんな感じ

//空のオブジェクト
Object.prototype.toString.call({})
結果:"[object Object]"

//文字列
Object.prototype.toString.call("a")
結果:"[object String]"

//数値
Object.prototype.toString.call(1)
結果:"[object Number]"

//null
Object.prototype.toString.call(null)
結果:"[object Null]"

//undefined
 Object.prototype.toString.call(undefined)
結果:"[object Undefined]"

//Boolean
 Object.prototype.toString.call(true)
結果:"[object Boolean]"

//Function
Object.prototype.toString.call(function(){})
結果:"[object Function]"

//正規表現
Object.prototype.toString.call(/abc/)
結果:"[object RegExp]"
20
24
4

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
20
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?