JavaScript: オブジェクトの型を確認する
JavaScriptで配列などのオブジェクトの型を確認(判定)したい場合は、 Object.prototype.toStringを使用します。
文字列などの基本データ型の場合はtypeof演算子で型を確認できますが、
配列やオブジェクトなどはtypeof演算子では「"object"」としか表示されません。
(関連記事:データ型を確認する typeof)
そこでObject.prototype.toStringを使用するとオブジェクトの型も確認できます。
Object.prototype.toStringを使ってデータ型を調べる場合は次のように記述します。
const toString = Object.prototype.toString; console.log(toString.call(調べたいオブジェクト));
次のサンプルコードでは、Object.prototype.toStringを使って 数値・文字列・真偽値・配列・オブジェクト・null・undefinedなどの データ型を確認しています。
const toString = Object.prototype.toString;
// 数値
console.log(toString.call(10)); // [object Number]
// 数値
console.log(toString.call(3.1415)); // [object Number]
// 文字列
console.log(toString.call("hello world")); // [object String]
// 真偽値
console.log(toString.call(true)); // [object Boolean]
// 配列
console.log(toString.call([1, 2, 3])); // [object Array]
// オブジェクト
console.log(toString.call({a: 1, b: 2})); // [object Object]
// null
console.log(toString.call(null)); // [object Null]
// undefined
console.log(toString.call(undefined)); // [object Undefined]