if(negetive number)是真的吗?js有问题吗?

bhb*_*bhb 1 javascript truthiness

js有问题吗?

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

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

the*_*eye 9

根据ECMA 5.1标准规范,下表用于确定表达式的真实性

+-----------------------------------------------------------------------+
| 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                                                  |
+-----------------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)


Mos*_*sho 7

唯一的数字是"falsey"(因此会评估false并且不会传递'if'语句)0.其余的都是"真实的",甚至是负面的.

您可以在控制台中测试它!!-1.这意味着将值转换为相反的布尔值,并重复一次.首先!-1回报false和第二回报true.这是将表达式转换为其布尔等效项的最常用方法.