null 与 undefined 区别

 

  • 相似性

  1、在if语句中,都会自动被转为false

  
  if (!undefined){  
    console.log("undefined is false"); //undefined is false
  }

  if(!null){
    console.log("null is false"); //null is false
  }

  2、赋值给变量,几乎没有区别

   
  var a = undefined;

  var b = null;
  

  3、相等运算符直接报告两者相等

  console.log(undefined == null); //true
  • 区别

  两者做全等比较时,返回false。

  console.log(undefined === null); //false

  原因:nul 为Null类型,代表”空值“,代表空对象指针,使用typeof运算符得到 ”object“ ,所以可以认为它是一个特殊的对象值。undefined 为Undefined类型,实际上 undefined值是派生自 null值的。

  • 目前用法

  null 表示“没有对象”,即该处不应该有值。典型用法:

  1、作为函数参数,表示该函数的参数不是对象。

  2、作为对象原型链的终点

  Object.getPrototypeOf(Object.prototype)
  
  //null

  undefined 表示“缺少值”,就是此处应该有一个值,但是还没有定义。

  1、变量被声明了,但是还没有赋值时,就等于 undefined

  2、调用函数时,应该提供的参数没有提供,该参数就等于 undefined

  3、对象没有赋值的属性,该属性的值为 undefined

  4、函数没有返回值时,默认返回 undefined

  var a;
  console.log(a); //undefined
  
  function test(b){console.log(b)}
  test(); //undefined

  var C = new Object();
  console.log(C.d); //undefined

  var X = test();
  console.log(X); //undefined

  

 

posted @ 2019-07-15 13:28  足迹#  阅读(324)  评论(0编辑  收藏  举报