| 類型 | 關鍵字 | 示例 | typeof 結果 |
|---|---|---|---|
| Number | number | 42, 3.14, NaN, Infinity | "number" |
| String | string | "hello", 'world', `模板` | "string" |
| Boolean | boolean | true, false | "boolean" |
| Null | null | null | "object" (著名 Bug) |
| Undefined | undefined | undefined, 未聲明變量 | "undefined" |
| Symbol (ES6) | symbol | Symbol('id') | "symbol" |
| BigInt (ES2020) | bigint | 9007199254740991n | "bigint" |
| Object | object | {}, [], function(){}, new Date() | "object" (函數為 "function") |
typeof "hello"; // "string"
typeof 123; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof Symbol(); // "symbol"
typeof 123n; // "bigint"
typeof null; // "object" (ECMAScript 歷史遺留 Bug)
typeof {}; // "object"
typeof []; // "object"
typeof function(){}; // "function" (特殊: 函數可調用)
typeof new Date(); // "object"
// 數組
Array.isArray([]); // true (ES5+ 標準)
Object.prototype.toString.call([]); // "[object Array]" (通用)
// null
val === null; // 唯一可靠方式
Object.prototype.toString.call(null); // "[object Null]"
JS 允許不同類型直接運算,引擎自動轉換:
"5" - 2; // 3 (字符串隱式轉數字)
"5" + 2; // "52" (數字轉字符串拼接)
true + 1; // 2 (boolean 轉數字)
null + 1; // 1 (null → 0)
undefined + 1; // NaN
[] + {}; // "[object Object]" (對象轉字符串)
[] + []; // "" (空數組 → 空字符串)
null == undefined; // true (規定相等)
null === undefined; // false (類型不同)
0 == ""; // true
0 === ""; // false
NaN == NaN; // false (NaN 不等於自身)
Object.is(NaN, NaN); // true (ES6 新增同值相等)
function getType(val) {
if (val === null) return 'null';
if (typeof val !== 'object') return typeof val;
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
// 測試
getType([]); // "array"
getType({}); // "object"
getType(null); // "null"
getType(/re/); // "regexp"
getType(new Date()); // "date"