var a = "hello";
var b = "string";
if (typeof a == b) { // 條件為 false
console.log("兩者一樣");
} else {
console.log("兩者不一樣"); // 執行這裡
}
typeof a 回傳字串 "string"。程式碼比較的是 typeof a (字串) 與 b (字串變數),而非 typeof a === typeof b。若 b 不是字面值 "string",條件即為假。
| 目的 | 寫法 |
|---|---|
| 檢查 a 型別是否為字串 | typeof a === "string" |
| 比較 a、b 型別是否相同 | typeof a === typeof b |
| 比較 a、b 值與型別皆相同 | a === b |
typeof "str" // "string"
typeof 123 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof null // "object" (著名 bug)
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
typeof 運算子優先級高,typeof a == b 解析為 (typeof a) == b。記得加括號或直接用字面值比較:typeof a === "string"。