js有什么问题吗?
if("hello".indexOf("world")) { // I forgot to add > -1 here
console.log("hello world");
}
基本上if(-1)
是真的。这怎么可能?我花了一整天的时间来解决这个问题。是否有列出此类内容的列表?或可用于捕获此类事物的工具。
js有什么问题吗?
if("hello".indexOf("world")) { // I forgot to add > -1 here
console.log("hello world");
}
基本上if(-1)
是真的。这怎么可能?我花了一整天的时间来解决这个问题。是否有列出此类内容的列表?或可用于捕获此类事物的工具。
根据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 |
+-----------------------------------------------------------------------+
唯一“错误”的数字(因此会评估为false
而不通过“if”语句)是0
. 其余的都是“真实的”,甚至是负面的。
您可以在控制台中使用!!-1
. 这意味着将值转换为相反的布尔值,并重复一次。第一个!
on-1
返回false
,第二个返回true
。这是将表达式转换为其等效布尔值的最常用方法。
你可以在这里看到真值和假值
以下值总是虚假的:
- 错误的
- 0(零)
- ""(空字符串)
- 空值
- 不明确的
- NaN(一个特殊的数字值,意思是非数字!)
所有其他值都是真值,包括“0”(引号中的零)、“false”(引号中的假)、空函数、空数组和空对象。
如前所述,只有 0(考虑数字)等于零。但是是的,在 javascript 中有一个等于 false 的列表,它们是:
当comapred 为false 时,其他所有内容都返回false。例如 -1 == 假 -> 假