LoginSignup
0
1

More than 3 years have passed since last update.

Javascript データ型の種類 勉強用

Posted at

Javascriptのデータ型の種類

JavaScriptにおける型とは、数値(number)、文字列(string)、ブール値(boolean)、null、undefinedの5つのプリミティブ型があります。これらはtypeof演算子を用いて判別する事が出来ます。ただし、nullだけは仕様に反して'object'を返します。

判定
String 文字列
number 数値
boolean true false
undefined undefined
object null

typeofでの型の判定方法

console.log((typeof "文字列"));    //String
console.log((typeof 1));          //number
console.log((typeof true));       //boolean
console.log((typeof undefined));  //undefined
console.log((typeof null));       //object

オブジェクトの[[Class]]を用いた判定

様々なオブジェクト(Object、Array等)の判別は出来ない。しかし、「型」の判定をしたいと言う場合、実際にはArrayやObjectの区別をしたい場合が多い。
そこで、Object.prototype.toStringを用いて、オブジェクトの[[Class]]内部プロパティを取得する方法がしばしばとられる。出力は、[object [[Class]]]という形式。

let toString = Object.prototype.toString

toString.call({});                // [object Object]  
toString.call([]);                // [object Array]
toString.call(function() {});    // [object Function]
toString.call(new Error());       // [object Error]
toString.call(new Date());        // [object Date]
toString.call(JSON);              // [object JSON]
toString.call(Math);              // [object Math]
toString.call(new RegExp());      // [object RegExp]
toString.call(new String('str')); // [object String]
toString.call(new Number(1));     // [object Number]
toString.call(new Boolean(true)); // [object Boolean]

0
1
1

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