js有问题吗?
if("hello".indexOf("world")) { // I forgot to add > -1 here
console.log("hello world");
}
基本上if(-1)
是真的。这怎么可能?我花了一整天才解决这个问题。是否列出了列出这些类型的列表?或者可以用来捕捉这些东西的工具。
答案 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的列表,那些是:
comapred为false时的所有其他内容都返回false。例如-1 == false - >假