JavaScript中0, "", null, false, undefined返回的Boolean类型均为false。然而它们所指的并不是同一个概念,需要加以区分。
首先先看一段代码:
document.write(typeof(0)) //number
document.write(typeof("")) //string
document.write(typeof(null)) //object
document.write(typeof(false)) //boolean
document.write(typeof(undefined)) //undefined
从上述代码可以看出:0是数字类型对象,空字符串是字符串类型对象,null是object对象,false是布尔类型对象,undefined还是undefined类型.。
对于null为什么是一个object对象,这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来。可以将它理解为一个不存在的对象的占位符。
使用==操作将0和false与其他对象进行比较:
document.write(false==undefined); //false
document.write(false==null); //false
document.write(undefined==0); //false
document.write(null==0); //false
document.write(""==0); //true
document.write(false==0); //true
document.write(false==""); //true
document.write(null==undefined); //true
观察可发现:0、""和false是相等的,null和undefined是相等的,而undefined和null并不等于false对象。
可以把0、""和false归为一类,称之为“假值”,把null和undefined归为一类,称之为“空值”。假值还是一个有效的对象,所以可以对其使用toString等类型相关方法,空值则不行。
document.write(false.toString()); // false
document.write("".length); // 0
document.write((0).toString()); // 0
document.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在前面已经说过。