在 JavaScript 中,为什么“0”等于 false,但是当通过 'if' 测试时,它本身不是 false?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7615214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?
提问by nonopolarity
The following shows that "0"
is false in Javascript:
以下显示"0"
在 Javascript中为 false:
>>> "0" == false
true
>>> false == "0"
true
So why does the following print "ha"
?
那么为什么会打印以下内容"ha"
呢?
>>> if ("0") console.log("ha")
ha
回答by Joe
Tables displaying the issue:
显示问题的表格:
and ==
和 ==
Moral of the story use ===
故事寓意===
table generation credit: https://github.com/dorey/JavaScript-Equality-Table
回答by jdi
The reason is because when you explicitly do "0" == false
, both sides are being converted to numbers, and thenthe comparison is performed.
原因是因为当你显式执行时"0" == false
,双方都被转换为数字,然后进行比较。
When you do: if ("0") console.log("ha")
, the string value is being tested. Any non-empty string is true
, while an empty string is false
.
当您执行以下操作时:if ("0") console.log("ha")
,正在测试字符串值。任何非空字符串都是true
,而空字符串是false
。
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
(From Comparison Operatorsin Mozilla Developer Network)
等于 (==)
如果两个操作数的类型不同,JavaScript 会转换操作数,然后应用严格的比较。如果操作数是数字或布尔值,则操作数尽可能转换为数字;else 如果任一操作数是string,则另一个操作数在可能的情况下转换为 string 。如果两个操作数都是对象,那么当操作数引用内存中的同一个对象时,JavaScript 会比较内部引用是否相等。
(从比较运算符在Mozilla开发者网络)
回答by Incognito
It's according to spec.
这是根据规范。
12.5 The if Statement ..... 2. If ToBoolean(GetValue(exprRef)) is true, then a. Return the result of evaluating the first Statement. 3. Else, ....
ToBoolean, according to the spec, is
根据规范,ToBoolean 是
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
抽象操作 ToBoolean 根据表 11 将其参数转换为 Boolean 类型的值:
And that table says this about strings:
那个表格是关于字符串的:
The result is false if the argument is the empty String (its length is zero); otherwise the result is true
如果参数是空字符串(其长度为零),则结果为假;否则结果为真
Now, to explain why "0" == false
you should read the equality operator, which states it gets its value from the abstract operation GetValue(lref)
matches the same for the right-side.
现在,解释为什么"0" == false
您应该阅读相等运算符,该运算符声明它从抽象操作GetValue(lref)
中获取其值与右侧相同。
Which describes this relevant part as:
将这一相关部分描述为:
if IsPropertyReference(V), then a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get be the special [[Get]] internal method defined below. b. Return the result of calling the get internal method using base as its this value, and passing GetReferencedName(V) for the argument
Or in other words, a string has a primitive base, which calls back the internal get method and ends up looking false.
或者换句话说,一个字符串有一个原始基础,它回调内部的 get 方法并最终看起来是假的。
If you want to evaluate things using the GetValue operation use ==
, if you want to evaluate using the ToBoolean
, use ===
(also known as the "strict" equality operator)
如果要使用 GetValue 操作使用来评估事物==
,如果要使用, 进行评估ToBoolean
,请使用===
(也称为“严格”相等运算符)
回答by bobince
It's PHP where the string "0"
is falsy (false-when-used-in-boolean-context). In JavaScript, all non-empty strings are truthy.
PHP 中的字符串"0"
为假(false-when-used-in-boolean-context)。在 JavaScript 中,所有非空字符串都是真值。
The trick is that ==
against a boolean doesn't evaluate in a boolean context, it converts to number, and in the case of strings that's done by parsing as decimal. So you get Number 0
instead of the truthiness boolean true
.
诀窍是,==
针对布尔值不会在布尔上下文中进行评估,它会转换为数字,并且在字符串的情况下是通过解析为十进制来完成的。所以你得到 Number0
而不是 truthiness boolean true
。
This is a really poor bit of language design and it's one of the reasons we try not to use the unfortunate ==
operator. Use ===
instead.
这是一种非常糟糕的语言设计,也是我们尽量不使用不幸的==
运算符的原因之一。使用===
来代替。
回答by Thava
// I usually do this:
x = "0" ;
if (!!+x) console.log('I am true');
else console.log('I am false');
// Essentially converting string to integer and then boolean.
回答by Jason Gennaro
Your quotes around the 0
make it a string, which is evaluated as true.
你周围的引号0
使它成为一个字符串,它被评估为真。
Remove the quotes and it should work.
删除引号,它应该可以工作。
if (0) console.log("ha")
回答by Narendra Yadala
It is all because of the ECMA specs ... "0" == false
because of the rules specified here http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3...And if ('0')
evaluates to true because of the rules specified here http://ecma262-5.com/ELS5_HTML.htm#Section_12.5
这完全是因为 ECMA 规范......"0" == false
因为这里指定的规则http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3...并且if ('0')
由于这里指定的规则而评估为真http:// /ecma262-5.com/ELS5_HTML.htm#Section_12.5
回答by Jollymorphic
The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true
. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).
“if”表达式测试真实性,而双等式测试与类型无关的等价性。正如这里的其他人指出的那样,字符串总是真实的。如果 double-equal 测试其两个操作数的真实性,然后比较结果,那么您将得到直观假设的结果,即("0" == true) === true
. 正如 Doug Crockford 在他出色的JavaScript: the Good Parts 中所说,“[== 强制其操作数的类型] 的规则复杂且难以记住......缺乏传递性令人担忧。” 只需说其中一个操作数被强制类型强制匹配另一个,并且“0”最终被解释为数字零,
回答by Vishnu K. Panicker
==Equality operator evaluates the arguments after converting them to numbers. So string zero "0" is converted to Number data type and boolean false is converted to Number 0.So
==相等运算符在将参数转换为数字后计算参数。 所以字符串零“0”被转换为数字数据类型,布尔值被转换为数字0。所以
"0" == false // true
"0" == false // true
Same applies to `
同样适用于`
false == "0" //true
false == "0" //true
===Strict equality check evaluates the arguments with the original data type
===严格的相等性检查使用原始数据类型评估参数
"0" === false // false, because "0" is a string and false is boolean
"0" === false // false, because "0" is a string and false is boolean
Same applies to
同样适用于
false === "0" // false
false === "0" // false
In
在
if("0") console.log("ha");
if("0") console.log("ha");
The String "0" is not comparing with any arguments, and string is a true value until or unless it is compared with any arguments. It is exactly like
字符串“0”不与任何参数进行比较,并且字符串是真值,直到或除非它与任何参数进行比较。它就像
if(true) console.log("ha");
if(true) console.log("ha");
But
但
if (0) console.log("ha"); // empty console line, because 0 is false
if (0) console.log("ha"); // empty console line, because 0 is false
`
`
回答by Sachin
This is because JavaScript uses type coercion in Boolean contexts and your code
这是因为 JavaScript 在布尔上下文和您的代码中使用类型强制
if ("0")
will be coerced to true in boolean contexts.
在布尔上下文中将被强制为真。
There are other truthy values in Javascript which will be coerced to true in boolean contexts, and thus execute the if block are:-
Javascript 中还有其他真值,它们将在布尔上下文中被强制为真,因此执行 if 块是:-
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)