前言
if (!undefined) { console.log('undefined is false'); } // undefined is false if (!null) { console.log('null is false'); } // null is false if (!0) { console.log('0 is false'); } // null is false if (undefined == null) { console.log(true); } // true
通过上面的知识点,我们来看下面的做法:
js判断undefined
以下是不正确的做法:
var a = undefined; if (a == undefined) { console.log("undefined"); }
由前言的知识可知,null==undefined成立,所以这种情况不排除a是null,当然如果要检测一个变量是否为null或undefined可以用这种方法。
以下是正确的作法:
//方法一 var a = undefined; if (a === undefined) { console.log("undefined"); } //方法二 var a = undefined; if (typeof(a) == "undefined") { alert("undefined"); }
来说一下方法二:
typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined",所以可以用此方法,注意不要写成if (typeof(a) == undefined)
js判断null
以下是不正确的做法:
var a = null; if (a == null) { console.log("null"); }
同理(同js判断undefined的不正确方法)。
var a = null; if (!a) { console("null"); }
该方法不排除a是0或者undefined。
var a = null; if (typeof(a) == "null") { console.log("null"); }
typeof 返回六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined",不包括"null"。
以下是正确的作法:
var a = null; if (!a && typeof(a)!="undefined" && a!=0) { console.log("null"); }