JS中undefined表示变量没有定义或从来没有赋值,而null是空对象,是有值的。
例如:
var a; alert( typeof a); //"undefined" a = null ; alert( typeof null ); //"object" |
JS中==比较为弱类型比较,JS会自动进行类型转换,然后返回值的比较结果。
而===为强类型比较,即必须类型与值同时相同,才会相等。
例如:
alert(0 == "0" ); //true alert(0=== "0" ); //false alert(undefined == null ); //true alert(undefined === null ); //false |
判断变量为null:
if (a === null ) // or if (a == null ) |
第一种方法,当a为undefined时返回false,
第二种方法,当a为undefined时返回true。
判断变量为undefined:
if ( typeof a === "undefined" ) // or if (a === undefined) // or if (a == undefined) |
第一、二种方法,当a为null时返回false,
第三种方法,当a为null时返回true。
还有一种使用falsey进行检查的方法:
if (!a) { // `a` is falsey, which includes `undefined` and `null` // (and `""`, and `0`, and `false`) } |
大部分翻译自stackoverflow:
JavaScript checking for null vs. undefined and difference between == and ===