JS中判斷null、undefined與NaN的方法

1.判斷undefined:函數

var  tmp = undefined;
if  ( typeof (tmp) ==  "undefined" ){ 
console.log( "undefined" );
}

說明:typeof 返回的是字符串,有六種可能:"number"、"string"、"boolean"、"object"、"function"、"undefined" code

2.判斷null:字符串

var  tmp =  null ;
if  (!tmp &&  typeof (tmp)!= "undefined"  && tmp!=0){ 
console.log( "null" );
}
3.判斷NaN:
var  tmp = 0/0;
if (isNaN(tmp)){
console.log( "NaN" );
}
說明:若是把 NaN 與任何值(包括其自身)相比獲得的結果均是 false,因此要判斷某個值是不是 NaN,不能使用 == 或 === 運算符。
提示:isNaN() 函數一般用於檢測 parseFloat() 和 parseInt() 的結果,以判斷它們表示的是不是合法的數字。固然也能夠用 isNaN() 函數來檢測算數錯誤,好比用 0 做除數的狀況。 
4.判斷undefined和null的關係:

var tmp = undefined;
if (tmp == undefined) {
console.log("undefined == undefined");
}string

var tmp = undefined;
if (tmp == null) {
console.log("null == undefined");
}io

結論:null == undefined console

5.判斷undefined、null與NaN:function

var tmp = null;
var tmp1 = undefined;
var tmp2 = NaN;
if (!tmp) {
console.log("null or undefined or NaN");
}
if (!tmp1) {
console.log("null or undefined or NaN");
}
if (!tmp2) {
console.log("null or undefined or NaN");
}class

結果:都打印object

相關文章
相關標籤/搜索