0. 前提
「JavaScriptコードレシピ集(技術評論社)」の下記を参照、データ型についてまとめました。
Chap4 データについて深く知る
- 074 データの型について知りたい
- 076 データの型を調べたい
1. データの型について知る
データ型 |
意味 |
プリミティブ型(基本型) |
データそのもの |
オブジェクト型(複合型) |
データを参照するデータ |
JavaScriptで取り扱う数値、文字列、真偽値、オブジェクトといった値はすべて「型」(データ型)という区切りで分けられます。その違いは、「データそのもの」か「データを参照するデータ」かです。プリミティブ型(基本型)は、数値、文字列などの「データそのもの」です。プリミティブ型はさらに6種類に分類されます。
(「JavaScriptコードレシピ集」P.174)
1.1 プリミティブ型
プリミティブ型 |
意味 |
データの例 |
Boolean |
真偽値の型 |
true,false |
String |
文字列の型 |
'鈴木'、'田中' |
Number |
数値の型 |
1,30 |
Undefined |
値が未定であることを示す型 |
undefined |
Null |
値が存在しないことを示す型 |
null |
Symbal |
シンボルの型 |
Symbol() |
// データ100を「参照」
const num = 100;
// データ'鈴木'を「参照」
const str = '鈴木';
1.2 オブジェクト型
オブジェクト型 |
意味 |
データの例 |
Object |
オブジェクトの型 |
プリミティブ型以外のすべて(Array、Object、Data等) |
// [配列]
// データ1,2,3を参照するデータ
const arr = [1, 2, 3];
// [連想配列]
// キーageでデータ18を、キーnameでデータ'鈴木'を参照するデータ
const obj = {
age: 18,
name: '鈴木'
};
// [配列]
// 3つのオブジェクト(Object)を参照するデータ
// 各オブジェクトはさらに数値や文字列データを参照
const arr = [
{id: 10, name:'鈴木'},
{id: 20, name:'田中'},
{id: 30, name:'田中'}
]
2. データの型を調べる
Syntax
データ型 |
typeofの結果 |
データの例 |
Undefined |
undefined |
undefined |
Null |
object |
null |
Boolean |
boolean |
true,false |
String |
string |
'松本','浜田' |
Symbol |
symbol |
Symbol() |
Number |
number |
1,10,20 |
Object(関数を除く) |
object |
[1,2,3],{id:10,name:’浜田’} |
関数 |
function |
function(){},class MyClass{} |
2.1 データ型の出力(console.log(typeof 値))
console.log(typeof true); // 'boolean'
console.log(typeof 10); // 'number'
console.log(typeof '鈴木'); // 'string'
console.log(typeof null); // 'object'
console.log(typeof undefined); // 'undefined'
console.log(typeof Symbol()) // 'Symbol'
console.log(typeof [1,2,3]); // 'object'
console.log(typeof {id: 10, name:'田中'}); // 'object'
console.log(
typeof function() {
console.log('test');
}
); // 'function'
console.log(typeof class MyClass {}); // 'function'