js中的null和undefined有什么区别以及判断方法

发布于 28 天前  70 次阅读


null是空的意思,正所谓:空即是色,色既是空!

咳咳咳搞错了再来一遍

null:本质是一个表示“”无值“的对象,算是一个特殊的值,undefined:为定义表示此处应该有一个值,但是还没有定义。

let a;
let b = null;

console.log(a == undefined); //true
comsole.log(b == null); //true

第一点,null的类型是objectm,需要注意:这是一个历史性的错误,只需要记住即可undefined的类型是undefined代码如下:

typeof null; //"object"
typeof undefined; //"undefined"

第二点,undefined转数为NaN,但null转数值为0

console.log(Number(null)); //0
console.log(Number(undefined)); //NaN

第三点,JSON会将undefined对于的key删除,这是应为JSON自身的转换原则。

console.log(JSON.stringify({ a: undefined})); //{}
console.log(JSON.stringify( {b: null} )); //{"b" :null}

判断通过=== 可以精确的判断 null和undefinde,然后通过 == null可以同时判断null和undefine,

console.log(undefined == null); //true
console.log(undefined == null); //一定要全等于判断为:false