简体   繁体   English

为什么此代码有效?

[英]Why does this code work?

I thought if statements weren't supposed to contain assignment operators but rather the comparison operators (==, ===) but this works perfectly. 我以为if语句不应该包含赋值运算符,而应该包含比较运算符(==,===),但这很完美。 Why? 为什么?

var foo = true,
    bar = true;
if (foo = true) {
    console.log('foo is true');
}

I was taught that this wouldn't work but I just found out that it does. 我被告知这是行不通的,但我发现它确实行得通。

What you're actually doing, is still comparing: 您实际上在做什么,仍在比较:

if ((foo = true) == true) ...

This is an 'abbreviation' for: 这是“缩写”:

foo = true;
if (foo == true) ...

So it does make sense =)! 所以这确实有意义=)!

From the ES5.1 specification (12.5) 根据ES5.1规范(12.5)

IfStatement :
    if ( Expression ) Statement  else Statement
    if ( Expression ) Statement

Any valid expression can be placed inside an if. 任何有效的表达式都可以放在if中。

foo = true is an expression and it evaluates to true. foo = true是一个表达式,其结果为true。

To avoid bugs like writing = instead of == in the future write it like 为了避免以后像写=而不是==这样的错误

if (true = foo) {

}

Which will throw a assignment error since you can't assign values to literal values like true 这将引发分配错误,因为您不能将值分配给像true文字值

The assignment is evaluated to true , beacuse JavaScript returns the value that it sets the variable to. 该赋值被评估为true ,因为JavaScript返回了将变量设置为的值。

var foo = true,
    bar = true;
if (foo = true) {
    console.log('foo is true');
}

becomes: 变成:

var foo = true,
    bar = true;
if (true) {
    console.log('foo is true');
}

which passes the if . 通过if Note that setting to false would not work, because the conditional would evaluate to false which does not pass the if . 请注意,设置为false将不起作用,因为条件条件的评估结果为false ,该条件未通过if

Specification about if : 规格大约if

if ( Expression ) Statement if(表达式)语句

You are using the assignment expression: 您正在使用赋值表达式:

AssignmentExpression : ConditionalExpression LeftHandSideExpression AssignmentOperator AssignmentExpression AssignmentExpression:ConditionalExpression LeftHandSideExpression AssignmentOperator AssignmentExpression

The = is specified as: =指定为:

Simple Assignment ( = ) 简单分配(=)

The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows: 生产的AssignmentExpression:LeftHandSideExpression = AssignmentExpression的评估如下:

... ...

2 . 2。 Let rref be the result of evaluating AssignmentExpression. 令rref为评估AssignmentExpression的结果。

3 . 3。 Let rval be GetValue(rref). 令rval为GetValue(rref)。

... ...

6. Return rval. 6.返回rval。

Tragically, you are in fact assigning foo to true. 可悲的是,您实际上是将foo分配为true。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM