null 和 undefined

本文详细解析了JavaScript中null与undefined的区别,包括它们的数据类型、比较运算符下的行为及类型转换特性。并介绍了如何高效地检查变量是否为undefined。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://blog.youkuaiyun.com/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’

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值