JS中判斷null、undefined與NaN
阿新 • • 發佈:2018-12-06
1.使用js查詢某個節點或屬性,如果該node或attr不存在,則返回undefined.
判斷undefined可採用typeof函式判斷:typeof(node) == “undefined”返回true即表示undefined
(typeof 返回的是字串型別有:”number”、”string”、”boolean”、”object”、”function”、”undefined” )
var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("undefined");
}
2.判斷null:
var tmp = null;
if (!tmp && typeof(tmp)!="undefined" && tmp!=0){
alert("null");
}
3.判斷NaN,NaN通常在計算出錯時出現,使用isNaN函式:
var tmp = 0/0;
if(isNaN(tmp)){
alert("NaN");
}
說明:如果把 NaN 與任何值(包括其自身)相比得到的結果均是 false,所以要判斷某個值是否是 NaN,不能使用 == 或 === 運算子。
提示:isNaN() 函式通常用於檢測 parseFloat() 和 parseInt() 的結果,以判斷它們表示的是否是合法的數字。當然也可以用 isNaN() 函式來檢測算數錯誤,比如用 0 作除數的情況。