寫到 str = "s"++ 之後跑出 NaN,才發現自己對這三個「空值」的判斷一直有點模糊。整理如下。
var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("undefined");
}
typeof 回傳的是字串,有六種可能結果:"number"、"string"、"boolean"、"object"、"function"、"undefined"。
var tmp = null;
if (!tmp && typeof(tmp) != "undefined" && tmp != 0){
alert("null");
}
var tmp = 0/0;
if (isNaN(tmp)){
alert("NaN");
}
這裡有個反直覺的特性:NaN 與任何值(包含它自己)比較,結果都是 false。所以判斷某值是否為 NaN,不能用 == 或 ===,必須用 isNaN()。
isNaN() 通常用來檢查 parseFloat() 與 parseInt() 的結果是否為合法數字,也可用來偵測算術錯誤,例如以 0 作除數的情形。
var tmp = undefined;
if (tmp == undefined)
{
alert("null or undefined");
}
var tmp = undefined;
if (tmp == null)
{
alert("null or undefined");
}
原理是 null == undefined 為 true。這源自於規格中的設計:兩者都是「假值」且在 == 的寬鬆比較下互相相等,但它們並不完全相同——null 通常代表「刻意設為空」,undefined 則多表示「尚未賦值」。
var tmp = null;
if (!tmp)
{
alert("null or undefined or NaN");
}
如果不需要嚴格區分,這個寫法就夠用了。
ES2015 之後有了更好的工具。判斷 undefined 與 null 可以寫成:
if (value === undefined || value === null) { /* ... */ }
// 或利用 == 的相等性
if (value == null) { /* 同時涵蓋 null 與 undefined */ }
判斷 NaN 則建議用 Number.isNaN(),因為全域的 isNaN() 會先做型別轉換,導致 isNaN("abc") 也回傳 true:
Number.isNaN(NaN) // true
Number.isNaN("abc") // false(全域 isNaN 則為 true)
Number.isInteger(5) // 判斷是否為整數
而 typeof 有個著名陷阱:typeof null === "object",這是 JavaScript 早期實作的遺留問題。要判斷是否為真正的物件,可寫成:
if (value !== null && typeof value === "object") { /* ... */ }
回到最初的例子,"s"++ 之所以得到 NaN,是因為自增運算子會先把字串轉成數字,而 "s" 無法轉成合法數字,於是得到 NaN,此後再參與算術運算也會持續是 NaN——這也是為什麼及早用 Number.isNaN() 檢查計算結果是個好習慣。