JS中Null与Undefined的区别

  Undefined的类型只有一个值,即特殊的undefined。在使用var声明变量但未对其加以初始化时这个变量的值就是undefined。对未初始化的变量执行typeof操作符会返回undefined值,而对未声明的变量执行typeof操作符同样也会返回undefined值。

  var oValue;  

  alert(oValue == undefined); //output "true"  

 

  Null类型是第二个只有一个值的数据类型,这个特殊的值是null。从逻辑角度来看,null值表示一个空对象指针,而这也正是使用typeof操作符检测null值时会返回"object"的原因。

  alert(null == document.getElementById('notExistElement'));  

  当页面上不存在id为"notExistElement"的DOM节点时,这段代码显示为"true",因为我们尝试获取一个不存在的对象。

 

  用相等操作符==比较undefined和null时返回true;

  用全等操作符===比较undefined和null时返回true;

 

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

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

  (2) 作为对象原型链的终点。

  Object.getPrototypeOf(Object.prototype)  // null

 

  undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。典型用法是:

  (1)变量被声明了,但没有赋值时,就等于undefined。

  (2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。

  (3)对象没有赋值的属性,该属性的值为undefined。

  (4)函数没有返回值时,默认返回undefined。

  var i;  i

  // undefined  

 

  function f(x){console.log(x)} 

  f() // undefined  

 

 

  var  o = new Object(); 

  o.p // undefined  

 

  var x = f(); 

  x // undefined

posted @ 2017-06-14 22:01  sakuramoon  阅读(153)  评论(0编辑  收藏  举报