一个比喻教你搞清楚null和undefined的区别

269 阅读1分钟
<script>
    /* 
    1. undefined : 未定义。 当变量只声明,但是没有赋值。此时默认值是undefined
        * 说人话 : undefined相当于期房。 买了房,但是房子还没建出来。(未定义)

    2. null : 有定义。 定义的值是空值。
        * 说人话 : null相当于毛坯房。买了房,但是房子没住人,里面是空的。(空值)
    */  
   
    //相同点 : (1)值相等 (2)转布尔类型都是false
    console.log( undefined == null )//true
    console.log( Boolean(undefined) )//false
    console.log( Boolean(null) )//false

    //不同点 : (1)数据类型不同  (2)转number类型值不同
    console.log( undefined === null )//false
    console.log( Number(undefined) )//NaN
    console.log( Number(null) )//0
    
</script>