JS 分為基本類型(7 種)與引用類型(Object)。本文系統梳理各類型特性、轉換規則、typeof/instanceof 檢測細節。
| 類型 | 關鍵字 | 值範圍/特點 | typeof 結果 |
|---|---|---|---|
| Undefined | undefined | 聲明未賦值 | 'undefined' |
| Null | null | 空對象指針 | 'object' (歷史 Bug) |
| Boolean | boolean | true/false | 'boolean' |
| Number | number | IEEE754 雙精度、NaN、Infinity | 'number' |
| String | string | UTF-16 字符序列 | 'string' |
| Symbol | symbol | 唯一標識符 (ES6) | 'symbol' |
| BigInt | bigint | 任意精度整數 (ES2020) | 'bigint' |
undefined:變量聲明未初始化、對象無此屬性、函數無返回值、參數未傳遞。null:主動表示「無對象」,語義明確。typeof null === 'object' 是公認 Bug(不會修復)。null == undefined // true,但 null === undefined // false。| 類型 | 轉為 true | 轉為 false |
|---|---|---|
| Boolean | true | false |
| String | 非空字符串 | '' (空串) |
| Number | 非 0、非 NaN | 0, -0, NaN |
| Object | 任意對象 | 無 (null 非對象) |
| Undefined | 無 | undefined |
| Null | 無 | null |
| Symbol | 任意 Symbol | 無 |
| BigInt | 非 0n | 0n |
Boolean(val) 或 !!val 顯式轉換,if/while/||/&&/?: 隱式轉換。
typeof NaN === 'number',NaN !== NaN,用 Number.isNaN() 或 Object.is(NaN, NaN) 判斷。0.1 + 0.2 === 0.30000000000000004,金融計算用整數(分)或 decimal.js。Number.MAX_SAFE_INTEGER = 2^53-1,超出精度丟失,用 BigInt。| 函數 | 解析規則 | 返回類型 | 典型用途 |
|---|---|---|---|
| Number() | 嚴格:整串必須合法數值 | Number | 通用轉換 |
| parseInt() | 從左解析至首個非數字,支持進制 | Number | 提取整數、解析 CSS 值 |
| parseFloat() | 從左解析至首個非浮點字符 | Number | 提取浮點數 |
Number('123px'); // NaN
parseInt('123px'); // 123
parseFloat('1.5px'); // 1.5
parseInt('0x10'); // 16 (十六進制)
parseInt('10', 2); // 2 (二進制)
// 1. 基本類型(含 null/array/function)
function typeOf(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
// 2. 引用類型構造函數判斷
arr instanceof Array; // 同框架可靠
Array.isArray(arr); // 跨框架推薦
fn instanceof Function; // 函數判斷
// 3. 空值檢測
val == null; // 僅 null/undefined 為 true (利用 == 隱式轉換)
val === null || val === undefined; // 顯式
掌握 7 大基本類型特性、轉換規則表、Number/parseInt/parseFloat 差異、NaN 判斷、Object.prototype.toString 萬能檢測,是寫出健壯 JS 代碼的基礎。現代開發優先用 Number.isNaN、Array.isArray、BigInt 等標準 API。