首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript typeof 比較陷阱:typeof a === b 錯誤分析

     編輯:程式設計疑難解答

錯誤程式碼

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 回傳值對照表

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"。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved