Javascript中null, undefined, NaN比较

[color=blue]a[/color]. null是关键字,不能用作函数或变量的名称;undefined是Global对象的一个属性:

alert('undefined' in window); // true
alert(undefined in window); // true


[color=blue]b[/color]. null是特殊的object(空对象, 没有任何属性和方法);undefined是undefined类型的值,未定义的值和定义未赋值的为undefined;NaN是一种特殊的number:

document.writeln(typeof null); // object
document.writeln(typeof undefined); // undefined
document.writeln(typeof granularity); // undefined
var heuristic;
document.writeln(typeof heuristic); // undefined
document.writeln(typeof NaN); // number


[color=blue]c[/color]. 对象模型中,所有的对象都是Object或其子类的实例,但null对象例外:

document.writeln(null instanceof Object); // false


[color=blue]d[/color]. null“等值(==)”于undefined,但不“全等值(===)”于undefined,NaN与任何值都不相等,与自己也不相等:

document.writeln(null == undefined); // true
document.writeln(null === undefined); // false
document.writeln(NaN == null); // false
document.writeln(NaN == undefined); // false
document.writeln(NaN == NaN); // false

可以用下面函数判断null和undefined:

function test(val) {
return val == null;
}
alert(test(null)); // true
alert(test(undefined)); // true


[color=blue]e[/color]. null与undefined都可以转换成false,但不等值于false:

document.writeln(!null, !undefined); // true true
document.writeln(undefined == false); // false
document.writeln(null == false); // false


[color=blue]f[/color]. null不等于0,但是计算中null会当做成0来处理;undefined计算的结果是NaN;NaN计算的结果也是NaN:

alert(null == 0); // false
alert(123 + null); // 123
alert(123 * null); // 0
alert(123 / null); // Infinity
alert(123 + undefined); // NaN
alert(123 * undefined); // NaN
alert(123 / undefined); // NaN
alert(123 + NaN); // NaN
alert(123 * NaN); // NaN
alert(123 / NaN); // NaN
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值