javascript 为什么 if("string") 将 "string" 评估为 true 但 if ("string"==true) 不会?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4923631/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:22:32  来源:igfitidea点击:

why does if("string") evaluate "string" as true but if ("string"==true) does not?

javascript

提问by munchybunch

Given the following code:

鉴于以下代码:

if ("string") {
    console.log('true!');
}
//logs "true" to the console
if ("string"==true) {
    console.log('true!');
}
//doesn't log anything

Why does this happen? I thought "string"was being cast to a number, as is the boolean. So truebecomes 1, and "string"becomes NaN. The second if statement makes sense, but I don't see why the first statement causes the inner loop to be evaluated. What's going on here?

为什么会发生这种情况?我认为"string"被强制转换为一个数字,布尔值也是如此。所以true成为1,并且"string"成为NaN。第二个 if 语句有意义,但我不明白为什么第一个语句会导致评估内部循环。这里发生了什么?

回答by John Kugelman

It is being cast to Boolean. Any non-empty string evaluates to true.

它被转换为布尔值。任何非空字符串的计算结果为真。

From the ECMAScript Language Specification:

来自ECMAScript 语言规范

12.5 The ifstatement

Semantics

The production IfStatement: if (Expression)StatementelseStatementis evaluated as follows:

  1. Let exprRefbe the result of evaluating Expression.
  2. If ToBoolean(GetValue(exprRef)) is true, then
    • Return the result of evaluating the first Statement.
  3. Else,
    • Return the result of evaluating the second Statement.

9.2 ToBoolean

The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:

Table 11 - ToBoolean Conversions

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

12.5if声明

语义

生产IfStatement: if (Expression )Statement elseStatement评估如下:

  1. exprRef是计算Expression的结果。
  2. 如果 ToBoolean(GetValue( exprRef)) 为true,则
    • 返回评估第一个Statement的结果。
  3. 别的,
    • 返回评估第二个Statement的结果。

9.2 ToBoolean

抽象操作 ToBoolean 根据表 11 将其参数转换为 Boolean 类型的值:

表 11 - ToBoolean 转换

未定义:false
空:false
布尔值:结果等于输入参数(无转换)。
Number:如果参数为+0-0NaN,则结果为;否则结果为。 字符串:如果参数为空字符串(其长度为零),则结果为;否则结果为。 对象:真实



As far as the ==operator is concerned, it's complicated, but the gist of it is that if you compare a number to a non-number the latter is converted into a number. If you compare a boolean against a non-boolean, the boolean is first converted to a number, and then the previous sentence applies.

==运算符而言,它很复杂,但其要点是,如果将数字与非数字进行比较,则后者将转换为数字。如果将布尔值与非布尔值进行比较,则布尔值首先转换为数字,然后适用上一句。

See section 11.9.3 for details.

有关详细信息,请参阅第 11.9.3 节。

// Call this x == y.
if ("string" == true) 

// Rule 6: If Type(y) is Boolean,
//         return the result of the comparison x == ToNumber(y).
if ("string" == Number(true))

// Rule 5: If Type(x) is String and Type(y) is Number,
//         return the result of the comparison ToNumber(x) == y.  
if (Number("string") == Number(true))

// The above is equivalent to:
if (NaN == 1)

// And NaN compared to *anything* is false, so the end result is:
if (false)

回答by SLaks

Non-empty strings are truthy, but are not necessarily equivalent to true.

非空字符串是真实的,但不一定等价于true



==is a "soft" equality operator.
It uses type coercion to compare two equivalent objects as equal.

==是一个“软”相等运算符。
它使用类型强制来比较两个等效的对象是否相等。

All of the following are true:

以下所有说法都是正确的:

42 == "42"
0 == false
0 == ""
[] == ""
{} == "[object Object]"
"1" == true

Aribtrary strings are not equivlant to any primitive values. However

任意字符串不等同于任何原始值。然而



When you write if (something), the ifwill execute if somethingis "truthy".

当你写的时候if (something)if如果something是“真实的”就会执行。

All values are truthful except the following:

除以下内容外,所有值都是真实的:

  • false
  • 0
  • NaN
  • ""
  • null
  • undefined
  • false
  • 0
  • NaN
  • ""
  • null
  • undefined

回答by Archinamon

if ("string"===true)

Should be written this way.

应该这样写。

回答by Krumelur

"string" is a string which is not null. In JavaScript everything not being null evaluates "true". So: if("string") is the same as if("string" != null) but "string" is not true, it is still a string value.

“字符串”是一个不为空的字符串。在 JavaScript 中,所有不为 null 的都评估为“true”。所以: if("string") 与 if("string" != null) 相同,但 "string" 不是真的,它仍然是一个字符串值。

回答by Aleksey Vitebskiy

I think this is happening because in the first example, your "string" is a non-null object, which translates to true in this context, whereas in the second example, you're asking if this String object is the same as the Boolean object, which it's not, so it translates to false.

我认为这是因为在第一个示例中,您的“字符串”是一个非空对象,在此上下文中转换为 true,而在第二个示例中,您询问此 String 对象是否与布尔值相同对象,它不是,所以它转换为 false。

回答by naveen

if ("string") {
    console.log('true!');
}

As you may already know, if evaluates a boolean expression. So it checks

您可能已经知道, if 计算布尔表达式。所以它检查

if((Boolean)"string")

Since (bool)string is true it passes. But in the case of

由于 (bool)string 为真,所以它通过了。但是在这种情况下

if ("string"==true) {
    console.log('true!');
}

You are trying to equate a string with a bool, which obviously compares them and returns false.

您试图将字符串与 bool 等同起来,这显然将它们进行比较并返回 false。

回答by SoulWanderer

From the ECMA 262 reference, if you convert implicitly a String to Boolean, and the String is other than the empty String, it will evaluate to true.

根据 ECMA 262 参考,如果您将字符串隐式转换为布尔值,并且该字符串不是空字符串,则它将评估为真。

Check here

在这里查看

回答by Yuval Adam

Simple:

简单的:

if("string")is evaluated as a boolean. Any value that isn't falseis true, no conversion to number or anything of that sort.

if("string")被评估为布尔值。任何不是falseis 的值,都不会true转换为数字或任何类似的东西。

Comparing "string"to a boolean value truewill obviously yield false.

"string"布尔值相比,true显然会产生false.

回答by powtac

Because its JavaScript is like that. Check out all related Questions at the right side of this page.

因为它的 JavaScript 就是这样。查看此页面右侧的所有相关问题。