编程语言
首页 > 编程语言> > 在JavaScript中链接复合赋值运算符

在JavaScript中链接复合赋值运算符

作者:互联网

在C#中,

string s = "abc";
s += (s += s);
Console.WriteLine(s);

写道abcabcabc(http://ideone.com/pFNFX2).这很好,因为C#规范明确在7.16.2节中说过

the operation is evaluated as x = x op y, except that x is evaluated only once.

但是,在阅读ECMAScript 5.1语言规范第11.3.2节中对复合赋值运算符的描述时,我在这个运算符的语义中看不到这样的“只有一次”限定符.相反,我所看到的只是:

  1. Let lref be the result of evaluating LeftHandSideExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating AssignmentExpression.
  4. Let rval be GetValue(rref).
  5. Let r be the result of applying operator @ to lval and rval.
  6. Throw a SyntaxError exception if the following conditions are all true: (snipped)
  7. Call PutValue(lref, r).
  8. Return r.

因此,对我来说,无论如何都会出现以下JavaScript代码

var s = "abc";
s += (s += s);
alert(s);

会提醒abcabcabcabc(因为带括号的表达式中的第7行上的PutValue),但是,无论如何,它都会在Chrome 22中警告abcabcabc.

所以我的问题是:我是否误读了规范,或者Chrome(也许是V8?)做​​了不合适的事情,可以这么说?

解决方法:

所以我想如果你打开这个操作,你有:

s += (s += s);

s = s + (s += s);
s = s + (s = s + s);    // Can't actually have the "s = " part, it's really just "s + s"
s = s + (s + s);
s = s + s + s;

这意味着结果应该是“abcabcabc”.

标签:javascript,ecmascript-5,side-effects,compound-assignment
来源: https://codeday.me/bug/20190625/1287741.html