if(负数)是真的吗? js有问题吗?

时间:2014-04-07 06:29:22

标签: javascript truthiness

js有问题吗?

if("hello".indexOf("world")) { // I forgot to add > -1 here
    console.log("hello world");
}

基本上if(-1)是真的。这怎么可能?我花了一整天才解决这个问题。是否列出了列出这些类型的列表?或者可以用来捕捉这些东西的工具。

4 个答案:

答案 0 :(得分:9)

根据ECMA 5.1 Standard Specifications,下表用于确定表达式的真实性

+-----------------------------------------------------------------------+
| Argument Type | Result                                                |
|:--------------|------------------------------------------------------:|
| Undefined     | false                                                 |
|---------------|-------------------------------------------------------|
| Null          | false                                                 |
|---------------|-------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number        | The result is false if the argument is +0, −0, or NaN;|
|               | otherwise the result is true.                         |
|---------------|-------------------------------------------------------|
| String        | The result is false if the argument is the empty      |
|               | String (its length is zero); otherwise the result is  |
|               | true.                                                 |
|---------------|-------------------------------------------------------|
| Object        | true                                                  |
+-----------------------------------------------------------------------+

答案 1 :(得分:7)

唯一的数字是" falsey" (因此评估为false而不会传递' if'语句)0。剩下的就是" truthy"甚至是负面的。

您可以使用!!-1在控制台中对此进行测试。这意味着将值转换为相反的布尔值,并重复一次。 !上的第一个-1返回false,第二个true返回{{1}}。这是将表达式转换为其布尔等效项的最常用方法。

答案 2 :(得分:3)

你可以看到Truthy和Falsy Values here

  

以下值始终是假的:

     
      
  •   
  • 0(零)
  •   
  • "" (空字符串)
  •   
  •   
  • 未定义
  •   
  • NaN(一个特殊的数字值,意思是非数字!)
  •   
     

所有其他值都是真实的,包括" 0" (引号为零)," false"   (引号中为false),空函数,空数组和空对象。

答案 3 :(得分:0)

如前所述,只有0(考虑数字)相当于零。但是是的,在javascript中有一些等于false的列表,那些是:

  1. 未定义
  2. 空字符串""
  3. 数字0
  4. 数字NaN
  5. comapred为false时的所有其他内容都返回false。例如-1 == false - >假