美文网首页
null undefined

null undefined

作者: 练习时长2年半的个人练习生 | 来源:发表于2020-07-02 11:54 被阅读0次

区别

  • undefined: 声明了变量,但未赋值。例如:var a;

  • null:声明了某一变量,并赋值,只是值为空。例如:var obj = null, 用来释放内存.依然保持变量名存在

 typeof(null) //object
  console.log(null == undefined)//true
  console.log(null === undefined)//false

判断一个变量是否声明

因为尚不知变量是否声明,所以不能通过值来判断.可以通过判断变量的类型是否为undefined 来判断,但是不能通过变量的值(变量==='undefine')来判断

    console.log(typeof spx == 'undefined')//true
    console.log(spx === 'undefined')//会报refrenceError spx is not  defined

判断变量的值是否为空,直接通过(!变量)会很粗糙.不准确因为
以下几种情况都会为true

    console.log(!'')
    console.log(!null)
    console.log(!undefined)
    console.log(!0)

严谨的做法为


 let str;
    console.log(typeof str == 'undefined' && !str)

相关文章

网友评论

      本文标题:null undefined

      本文链接:https://www.haomeiwen.com/subject/nrwlqktx.html