【问题标题】:Javascript Truthy / Falsy OperationJavascript 真/假操作
【发布时间】:2018-07-25 01:01:45
【问题描述】:

我有一个关于 javascripttruthy / falsy 的问题

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

-1 == true //returns false

还有

-1 == false //returns false

有人能解释一下吗?我会很感激的。

【问题讨论】:

  • "truthy" 并不意味着“等于 true”,就像“positive” 并不意味着“等于 +1”。真实值有很多,true 只是其中之一。

标签: javascript casting truthiness


【解决方案1】:

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

-1 == Number(true)

-1 == Number(false)

依次是

-1 == 1

-1 == 0

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

Boolean(-1) == true //true

【讨论】:

  • 谢谢。当你解释它时才有意义。
【解决方案2】:

不,布尔值有点像 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

【讨论】:

    【解决方案3】:

    任何非零数评估为真,零评估为假。 这不等于等于真/假。

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

    if (-1) {
        true;
    } else {
        false;
    }
    

    【讨论】:

      【解决方案4】:

      除了 @James Thorpe 答案之外,如果您想识别零和非零数字,您可以使用以下代码:

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

      【讨论】:

        猜你喜欢
        • 2014-10-25
        • 1970-01-01
        • 1970-01-01
        • 2016-06-09
        • 2012-07-17
        • 2012-06-03
        • 2021-04-20
        • 2015-03-30
        相关资源
        最近更新 更多