核心區別
- `typeof x`** 返回字符串,表示基本類型 (`"number"`, `"string"`, `"boolean"`, `"undefined"`, `"symbol"`, `"bigint"`, `"function"`) 或 `"object"` (null、數組、對象、正則等)。
- `x instanceof Constructor`** 判斷 `x` 的原型鏈上是否存在 `Constructor.prototype`,返回布爾值。僅適用於對象 (引用類型)。
示例
typeof 123 // "number"
typeof "abc" // "string"
typeof {} // "object"
typeof [] // "object"
typeof null // "object" (著名bug)
typeof function(){} // "function"
[] instanceof Array // true
[] instanceof Object // true
new Date() instanceof Date // true
new Date() instanceof Object // true
123 instanceof Number // false (基本類型)
使用建議
- 判斷基本類型 → `typeof`。
- 判斷數組 → `Array.isArray(arr)` (最準確)。
- 判斷自定義類實例 → `instanceof`。
- 判斷 null → `x === null`。