javascript 参考错误:赋值中的左侧无效

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

ReferenceError: Invalid left-hand side in assignment

javascriptlogic

提问by Kevin

my code for a rock paper scissors game (called toss) is as follows:

我的石头剪刀布游戏(称为toss)的代码如下:

var toss = function (one,two) {
    if(one = "rock" && two = "rock") {
        console.log("Tie! Try again!");
    }
    // more similar conditions with `else if`
};

When I enter in the parameters

当我输入参数时

toss("rock","rock")

I get this error code:

我收到此错误代码:

"ReferenceError: Invalid left-hand side in assignment"

“参考错误:赋值中的左侧无效”

How to fix it? What this error means and what other cases when this error can happen?

如何解决?此错误意味着什么以及此错误可能发生的其他情况?

回答by Joseph Silber

You have to use ==to compare (or even ===, if you want to compare types). A single =is for assignment.

您必须使用==to compare (或者甚至===,如果您想比较类型)。单个=用于分配。

if (one == 'rock' && two == 'rock') {
    console.log('Tie! Try again!');
}

回答by Alexei Levenkov

Common reasons for the error:

错误的常见原因:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42instead of getFoo().theAnswer = 42or array indexing getArray() = 42instead of getArray()[0]= 42
  • 使用赋值 ( =) 而不是等式 ( ==/ ===)
  • 分配给函数的结果foo() = 42而不是传递参数 ( foo(42))
  • 只是缺少成员名称(即假设一些默认选择):getFoo() = 42而不是getFoo().theAnswer = 42或数组索引getArray() = 42而不是getArray()[0]= 42

In this particular case you want to use ==(or better ===- What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

在这种特殊情况下,您想使用==(或更好===- Javascript 中的 Type Coercion 到底是什么?)来检查相等性(例如if(one === "rock" && two === "rock"),但您收到错误的实际原因更棘手。

The reason for the error is Operator precedence. In particular we are looking for &&(precedence 6) and =(precedence 3).

错误的原因是Operator precedence。特别是我们正在寻找&&(优先级 6)和=(优先级 3)。

Let's put braces in the expression according to priority - &&is higher than =so it is executed first similar how one would do 3+4*5+6as 3+(4*5)+6:

在根据优先级的表达,让我们把括号-&&高于=所以它首先执行一个类似的会怎么做3+4*5+63+(4*5)+6

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

现在我们有类似于多个赋值的表达式,例如a = b = 42由于从右到左的关联性执行为a = (b = 42)。所以添加更多的大括号:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two)can't be evaluated to l-value that can be assigned to (in this particular case it will be valueof twoas truthy).

最后,我们到达实际的问题:("rock" && two)无法进行评估,以可分配给L值(在这个特定的情况下,将是two作为truthy)。

Note that if you'd use braces to match perceived prioritysurrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do &&on two strings "rock" && "rock"resulting in "rock"(which in turn is truthy) all the time due to behavior of logial &&:

请注意,如果您使用大括号将围绕每个“相等”的感知优先级与大括号相匹配,则不会出现错误。显然,这也产生了与您预期不同的结果 -由于logial && 的行为,更改了两个变量的值,而不是&&在两个字符串上进行操作,"rock" && "rock"从而导致"rock"(这反过来又是真的):

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}


For even more details on the error and other cases when it can happen - see specification:

有关错误和其他可能发生的情况的更多详细信息 - 请参阅规范:

Assignment

任务

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

LeftHandSideExpression = AssignmentExpression
...
如果以下条件全部为真,则抛出 SyntaxError 异常:
...
IsStrictReference(lref) 为真

Left-Hand-Side Expressions

左侧表达式

and The Reference Specification Typeexplaining IsStrictReference:

和解释 IsStrictReference的参考规范类型

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

...允许函数调用返回引用。承认这种可能性纯粹是为了宿主对象。本规范定义的内置 ECMAScript 函数没有返回引用,也没有规定用户定义的函数返回引用......

回答by Lukasz Dynowski

The same happened for me with eslintmodule. EsLinter throw Parsing error: Invalid left-hand side in assignment expressionfor await in second if statement.

我的eslint模块也发生了同样的情况。EsLinterParsing error: Invalid left-hand side in assignment expression在第二个 if 语句中抛出等待。

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolonat the end of line where await occurred.

听起来很奇怪,修复此错误的方法是添加; 在发生 await 的行末尾的分号

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}