当前位置: 代码迷 >> Web前端 >> null 跟 undefined
  详细解决方案

null 跟 undefined

热度:391   发布时间:2012-10-07 17:28:51.0
null 和 undefined

原文地址:http://blog.csdn.net/aimingoo/article/details/580336?

?

在JavaScript中,null与undefined曾一度使我迷惑。下面的文字,有利于你更清晰的认知它(或者让你更迷惑):

- null是关键字;undefined是Global对象的一个属性。
- null是对象(空对象, 没有任何属性和方法);undefined是undefined类?型的值。试试下面的代码:

console.log(typeof null);
?????? console.log(typeof undefined);

- 对象模型中,所有的对象都是Object或其子类的实例,但null对象例外://不明白,求真象
?????? console.log(null instanceof Object);
- null“等值(==)”于undefined,但不“全等值(===)”于undefined:
? ? ? ??console.log(null == undefined);
?????? console.log(null === undefined);
- 运算时null与undefined都可以被类型转换为false,但不等值于false:
?????? console.log(!null, !undefined);//一直都是这么用的
?????? console.log(null==false);//不明白,求真象
?????? console.log(undefined==false);//不明白,求真象

?

?

?

undefined跟null的区别,简单总结如下:


1. undefined == null //true
2. undefined === null //false
3. undefined === window.undefined //true
4. undefined === void 0 // true,性能优化技巧:判断一个变量是否是undefined,如果直接跟undefined对比的话,undefined的取值事实上会从window.undefined读取,如果window上有很多属性就会慢一些;而如果用void 0,就可以直接得到undefined,性能会快一些。
5. typeof undefined => ‘undefined’
6. typeof null ?=> ‘object’

?

?

  相关解决方案