我有一个关于javascript truthy / falsy的问题。
据我所知,包括负数在内的任何非零数都是真实的。但如果是这样,那为什么
-1 == true //returns false但同时也
-1 == false //returns false有人能说点什么吗?我会很感激的。
发布于 2018-02-14 12:44:49
当使用带有数字操作数和布尔操作数的==运算符时,首先将布尔操作数转换为数字,并将结果与数字操作数进行比较。这使你的发言相当于:
-1 == Number(true)和
-1 == Number(false)这反过来又是
-1 == 1和
-1 == 0这说明了为什么您总是看到一个false结果。如果强制将转换发生在数值操作数上,则得到所需的结果:
Boolean(-1) == true //true发布于 2018-02-14 12:45:39
不,布尔值或者是0 (false),或者是1(真)。
下面是一个示例:
console.log(0 == false); // returns true => 0 is equivalent to false
console.log(1 == true); // returns true => 1 is equivalent to true
console.log(-1 == false); // returns false => -1 is not equivalent to false
console.log(-1 == true); // returns false => -1 is not equivalent to true
发布于 2018-02-14 12:49:58
任何非零数字计算为真,零计算为false。这不等于真/假。
在这里执行下面的代码(用不同的值替换-1 )可以帮助您理解这一点:
if (-1) {
true;
} else {
false;
}https://stackoverflow.com/questions/48787470
复制相似问题