逻辑运算符 || 在JavaScript中,0 表示 Boolean False ?!
在测试的中找solution时偶尔看到一段码,如下:
var test = 0 || -1 ;
console.log(test);
在console中,test 的值显示是-1。
所以一下子闷了一下,然后上 stackoverflow 提了个问题,才发觉自己原来是脑袋短路了,基本的这些概念居然忘记的精光,稍微整理一下:
MDN 上的解释是:
||: expr1 || expr2
(Logical OR)Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false..
&&: expr1 && expr2
(Logical AND)Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
而在JavaScript中,所有的值要不是为“truthy”就是为“falsy”
而在条件判断语句中(conditional statements),以下的值都被看待为false:
- false
- null
- undefined
- The empty string
""
(\''
) - The number 0
- The number NaN
并且除此之外的所有值都被看待为true。
那么最最上面我引用的那一段代码就好理解了:
var test = 0 || -1 ;
这个时候0为false,逻辑或(Logical OR)这个判断符就绕过它将变量test赋值为-1