javascript null与undefined的区别

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

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

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

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

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

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

null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象。典型用法是:

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

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

alert(null == document.getElementById('notExistElement'));  
alert(typeof undefined);   //output "undefined"  
alert(typeof null);        //output "object"  
alert(null == undefined);   //output "true"  

ECMAScript认为undefined是从null派生出来的,所以把它们定义为相等的。

alert(null === undefined); //output "false"  
alert(typeof null == typeof undefined); //output "false"  

null与undefined的类型是不一样的,所以输出"false"。而‘===’代表绝对等于,在这里null === undefined输出false。

posted @ 2017-09-25 22:26  Apple-fly  阅读(167)  评论(0编辑  收藏  举报