基本型別 (Primitive Types)
- String (字串)
- 用引號括起來的文字。
- 例:"Hello", 'World',
Hi ${name}
- Number (數字)
- 整數、浮點數、NaN、Infinity 都屬於 Number。
- 例:42, 3.14, NaN, Infinity
- BigInt (大整數)
- 可表示超過 Number.MAX_SAFE_INTEGER 的大數。
- 例:12345678901234567890n,BigInt(9007199254740991)
- Boolean (布林值)
- Undefined (未定義)
let x;
console.log(x); // undefined
- Null (空值)
- 代表「沒有值」的基本型別。
- 例:let y = null;
⚠️ 注意:typeof null === "object",這是 JavaScript 歷史遺留的 bug。
7.Symbol (符號)
- 唯一且不可變的值,常作為物件 key。
- 例:const id = Symbol("id");
參考型別 (Reference Type)
- Object (物件)
- 鍵值對集合,可以是一般物件、陣列、日期、正則表達式…
typeof "Hello" // "string"
typeof 123 // "number"
typeof 123n // "bigint"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (特例!)
typeof Symbol() // "symbol"
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
小結
- JavaScript 總共有 7 種基本型別 + 1 種物件型別 = 8 種資料型別。
- JavaScript 是 動態型別語言:變數可以在不同時間存放不同型別的值。
let x = 5; // number
x = "hello"; // string
x = false; // boolean