(1)typeof 用法
typeof 用來判斷運算數的型別,常見回傳結果如下:
運算數未定義時,回傳 "undefined"
運算數為數字時,typeof(x) = "number"
字串時,typeof(x) = "string"
布林值時,typeof(x) = "boolean"
物件、陣列和 null 時,typeof(x) = "object"
函數時,typeof(x) = "function"
需要特別注意的是,null 的 typeof 結果是 "object",這是 JavaScript 歷史遺留的行為,實務上要判斷 null 需另外處理。
(2)JS 判斷是否為空
var exp = null; if (!exp && typeof(exp)!="undefined" && exp!=0 && exp!='') { alert("is not null"); } 這段判斷同時排除了 undefined、0 與空字串等「假值」情況,能較嚴謹地判斷一個變數是否為真正的空值。以上就是 JS 判斷空值與 typeof 用法的詳解,希望對大家有所幫助。