1
1

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 3 years have passed since last update.

【JavaScript】Objectかどうか判定する方法

Last updated at Posted at 2019-12-11

Objectかどうか判定する方法

結論: Object.prototype.toString.call()を使う。

typeofを使用した場合

以下の出力結果を予想できますか?

console.js
console.log(typeof {});
console.log(typeof []);
console.log(typeof null);
console.log(typeof undefined);
result
> "object"
> "object"
> "object"
> "undefined"

Javascriptのtypeofでは、{}, [], nullの結果が全て"object"になります。

Object.prototype.toString.callを使用した場合

console.js
console.log(Object.prototype.toString.call({}));
console.log(Object.prototype.toString.call([]));
console.log(Object.prototype.toString.call(null));
console.log(Object.prototype.toString.call(undefined));
result
> "[object Object]"
> "[object Array]"
> "[object Null]"
> "[object Undefined]"

それぞれ[object *]のformatで出力されます。

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?