JavaScript学习笔记——js变量的布尔值

typeof(1): number
typeof(NaN): number
typeof(Number.MIN_VALUE): number
typeof(Infinity): number
typeof("123"): string
typeof(true): boolean
typeof(window): object
typeof(Array()): object
typeof(function(){}): function
typeof(document): object
typeof(null): object
typeof(eval): function
typeof(Date): function
typeof(sss): undefined
typeof(undefined): undefined

所有的对象都被当作 true。
当且仅当字符串为空时,该字符串被当false。
null 和 undefined 被当作 false。
当且仅当数字为零时,该数字被当作 false。

 

.想到一个好玩的,运行如下 javascript :
  if ('0') alert("'0' is true");
  if ('0' == false) alert("'0' is false");结果是,两次都 alert 了!那么 '0' 到底是 true 还是 false 呢?

答案是:在js做比较的时候,有这样的三条规则:

如果比较的两者中有bool,会把 bool 先转换为对应的 number,即 0 和 1
如果比较的双方中有一方为number一方为string,会把string转换为数字
把string直接转换为bool的时候,空字符串‘’转换为 false,除此外的一切字符串转换为 true

在第一次比较的时候,直接把 '0' 放在 if 的表达式中,相当于直接把 string 转换为 bool, !!'0' === true,所以是成立的
在第二次比较的时候,会先把 false 转换为 0,然后把 '0' 转换为 0, 左右两边都是0,于是也是成立的。
所以归根到底这是一个javascript中做比较的时候类型转换顺序的问题,个人觉得还是不是很合理的,不同的转换顺序得到的结果会不一样

posted @ 2014-06-24 10:08  刺客隐  阅读(587)  评论(0编辑  收藏  举报