加法赋值运算符和空字符串加法运算符有什么区别?

4

我有一个如下的代码:

var point = '';
point = '' + 12 + 34;
console.log(point); // output = 1234

var point = '';
point += + 12 + 34;
console.log(point); //output = 46

你能解释一下吗?

谢谢。


JavaScript有一个算术运算符和一个字符串运算符,它们完全执行不同的操作,但使用相同的符号(+)。这就是生活。 - Álvaro González
更多关于赋值运算符的使用,就我所了解的... http://www.ecma-international.org/ecma-262/6.0/#sec-assignment-operators-runtime-semantics-evaluation - ficuscr
@ÁlvaroGonzález - JavaScript有一个加法运算符,它根据其操作数的不同(数学运算或连接字符串)而变化其行为,而不是具有相同符号的两个单独的运算符:https://tc39.github.io/ecma262/#sec-addition-operator-plus - T.J. Crowder
主要原因是JavaScript太烂了 :) - Regis Portalez
4个回答

9
区别在于分组。这样写:
point += + 12 + 34;

相当于:

//              v-----------v---- note grouping
point = point + ( + 12 + 34 );
//                ^--- unary

所示的+是一元的+,在这里并没有起到任何作用,因为12已经是一个数字。所以我们有:
point = point + ( 12 + 34 );

翻译内容如下:

point = point + 46;

由于 point 初始值为 "",因此结果为 "46"(字符串类型)。


4

根据加法赋值运算符,使用该运算符与指定表达式result = result + expression完全相同。

你的expression+12 + 34,其计算结果为整数46

point = point + expression
point = point + (+12 + 34)
point = point + 46
point = ""    + 46
point = "46"

您可能会注意到,在最后一步中,""46相结合给我们带来了一个字符串"46"。同样,根据上述文档...

这两个表达式的类型决定了+=运算符的行为:

If                                                         Then
---                                                        ---
Both expressions are numeric or Boolean                    Add
Both expressions are strings                               Concatenate
One expression is numeric and the other is a string        Concatenate

这是第三种情况的示例。一个表达式是数字(46),另一个是字符串(""),所以这两个值连接起来就是"46"

4
在第一种情况下,发生以下情况:
  1. '' + 12 --> '12'(请注意,现在我们拥有一个字符串,而不是一个数字)
  2. '12' + 34 --> '1234' Javascript自动将数字34强制转换为字符串'34'以便求值表达式
相反,在第二种情况下,发生以下情况:
  1. +12 --> 12应用于数字12的一元运算符,什么也没发生
  2. 12 + 34 --> 46相当标准的总和
  3. '' + 46 --> '46'空字符串加上数字46,结果为字符串'46'

1
The addition assignment operator `(+=)` adds a value to a variable.
`x += y` means  `x = x + y`
The `+=` assignment operator can also be used to add (concatenate) strings:

Example: 

    txt1 = "What a very ";
    txt1 += "nice day";

The result of txt1 will be:

    What a very nice day

On the other hand adding empty String `''` will make javascript to
confuse Addition & Concatenation.
Addition is about adding numbers.
Concatenation is about adding strings.



    var x = 10 + 5;          // the result in x is 15
    var x = 10 + "5";        // the result in x is "105"

请勿将非代码格式的代码示例格式化到文本中。使用CTRL+K使您的代码成为代码示例格式。 - davecar21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接