JavaScript中0, "", null, false, undefined的区别

来源:互联网 发布:肖像权网络侵权管辖 编辑:程序博客网 时间:2024/05/19 13:30

JavaScript中0, "", null, false, undefined返回的Boolean类型均为false。然而它们所指的并不是同一个概念,需要加以区分。

首先先看一段代码:

document.write(typeof(0))//numberdocument.write(typeof(""))//stringdocument.write(typeof(null))//objectdocument.write(typeof(false))//booleandocument.write(typeof(undefined))//undefined

从上述代码可以看出:0是数字类型对象,空字符串是字符串类型对象,null是object对象,false是布尔类型对象,undefined还是undefined类型.。

对于null为什么是一个object对象,这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来。可以将它理解为一个不存在的对象的占位符。

使用==操作将0和false与其他对象进行比较:

document.write(false==undefined);//falsedocument.write(false==null);//falsedocument.write(undefined==0);//falsedocument.write(null==0);//falsedocument.write(""==0);//truedocument.write(false==0);//truedocument.write(false=="");//truedocument.write(null==undefined);//true

观察可发现:0、""和false是相等的,null和undefined是相等的,而undefined和null并不等于false对象。
可以把0、""和false归为一类,称之为“假值”,把null和undefined归为一类,称之为“空值”。假值还是一个有效的对象,所以可以对其使用toString等类型相关方法,空值则不行。

document.write(false.toString());    // falsedocument.write("".length);         // 0document.write((0).toString());   // 0document.write(undefined.toString());   // throw exception "undefined has no properties"document.write(null.toString());        // "null has no properties"

undefined表示无效对象,null表示空对象。当声明的变量未被初始化时其默认值为undefined;如果被赋予null,则代表变量初始化值为空值。ECMAScript认为undefined是从null派生出来的所以把他们定义为相等。
以下两种方式会输出false:

document.write(null===undefined);  //false document.write(typeof(null)==typeof(undefined)); //false

因为===代表的是绝对等于,判断值及类型是否完全相等。null和undefined各自的type在前面已经说过。
                                             
0 0
原创粉丝点击