1

我有一个关于 javascript truthy / falsy 的问题

据我所知,包括负数在内的任何非零数都是真实的。但如果是这样的话,那为什么

-1 == true //returns false

但是也

-1 == false //returns false

有人可以阐明一下吗?我会很感激。

4

4 回答 4

6

==运算符与数字操作数和布尔操作数一起使用时,首先将布尔操作数转换为数字,然后将结果与数字操作数进行比较。这使您的陈述相当于:

-1 == Number(true)

-1 == Number(false)

依次是

-1 == 1

-1 == 0

这说明了为什么你总是看到false结果。如果你强制转换发生在数字操作数上,你会得到你想要的结果:

Boolean(-1) == true //true
于 2018-02-14T12:44:49.960 回答
1

不,布尔值有点像 0(假)或 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-14T12:45:39.463 回答
1

任何非零数计算为真,零计算为假。这与等于真/假不同。

执行下面的代码(并将 -1 替换为不同的值)可以帮助您理解这一点:

if (-1) {
    true;
} else {
    false;
}
于 2018-02-14T12:49:58.933 回答
0

In addition to the @James Thorpe answer, if you want to identify zero and non-zero numbers you can use the following code:

console.log(Math.abs(-1) > 0);
console.log(Math.abs(0) > 0);
console.log(Math.abs(1) > 0);

于 2018-02-16T07:06:26.657 回答