javascript truthy数字 [英] javascript truthy numbers

查看:80
本文介绍了javascript truthy数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于以下规则:

Falsy:


  • false

  • 0(零)

  • ''或(空字符串)

  • null

  • undefinded

  • NaN(例如1/0的结果)

  • false
  • 0 (zero)
  • '' or "" (empty string)
  • null
  • undefinded
  • NaN (e.g. the result of 1/0)

Truthy:其他所有

我无法找到正确的解释,为什么在以下测试中,只有数字1评估为true

I fail to find the correct explanation as to why in following tests, only number 1 evaluates to "true"

0 == true ("false")
1 == true ("true")
2 == true ("false")
othernumber == true ("false")


推荐答案

truthy和falsy规则仅在值本身用作测试时适用,例如:

The "truthy" and "falsy" rules only apply when the value itself is being used as the test, e.g.:

var str = "";
if (str) {
    // It's truthy
} else {
    // It's falsy
}

== 有自己的,不同的规则集,用于确定其操作数的松散相等性,在规范的抽象平等比较算法中进行了详细解释:

== has its own, different, set of rules for determining the loose equality of its operands, which are explained thoroughly in the spec's Abstract Equality Comparison algorithm:



  1. 如果Type(x)与Type(y)相同,那么


    • 返回执行Strict Equality Comparison x === y的结果。


有关详细信息,请参阅规范那里列出了各种抽象操作,虽然名字几乎都说明了他们的所作所为。 (如果你看一下规格,你会在各个地方的 ToNumber 之前看到;我已经删除了它是逻辑NOT运算符,它是 a与突然完成相关的规范符号。

See the spec for the full details of the various abstract operations listed in there, although the names pretty much say what they do. (If you look at the spec, you'll see ! prior to ToNumber in various places; I've removed it above. It's not the logical NOT operator, it's a spec notation related to "abrupt completions.")

让我们按照你的 2 == true 示例:


  1. 类型不一样,所以继续前进

  2. x isn 't null,所以继续

  3. x未定义,所以继续前进

  4. 类型(x)确实是数字,但是类型(y) )不是String,所以继续

  5. Type(x)不是String,所以继续

  6. Type(x)不是布尔值,所以继续前进

  7. 类型(y)是布尔值,因此返回x == ToNumber(y)的结果


    • ToNumber(true)为1,由于2 == 1为false,结果为false

  1. The types aren't the same, so keep going
  2. x isn't null, so keep going
  3. x isn't undefined, so keep going
  4. Type(x) is indeed Number, but Type(y) is not String, so keep going
  5. Type(x) is not String, so keep going
  6. Type(x) is not Boolean, so keep going
  7. Type(y) is Boolean, so return the result of x == ToNumber(y)
    • ToNumber(true) is 1, and since 2 == 1 is false, the result is false

但是noti ce,第7步与 1 == true 示例不同:

But notice that step 7 is different for your 1 == true example:


  1. Type(y)是布尔值,所以返回结果x == ToNumber(y)


    • ToNumber(true)是1,因为1 == 1为真,结果为真

这篇关于javascript truthy数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆