添加赋值运算符和带有空字符串的加号运算符之间有什么区别?

时间:2018-05-29 16:10:48

标签: javascript

我的代码如下:

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

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

你能解释一下吗?

感谢。

4 个答案:

答案 0 :(得分:9)

区别在于分组。这样:

point += + 12 + 34;

相当于:

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

指示的+是一元+,由于12已经是数字,因此不会执行任何操作。所以我们有:

point = point + ( 12 + 34 );

是:

point = point + 46;

,由于point开始为"",因此"46"(字符串)。

答案 1 :(得分:4)

在第一种情况下,会发生这种情况:

  1. '' + 12 --> '12'(请注意,现在我们有一个字符串,而不是数字)
  2. '12' + 34 --> '1234' Javascript会自动将数字34强制转换为字符串'34'以评估表达式
  3. 相反,这就是第二种情况:

    1. +12 --> 12一元运算符应用于数字12,没有任何反应
    2. 12 + 34 --> 46相当标准的总和
    3. '' + 46 --> '46'空字符串求和为46,结果为字符串'46'

答案 2 :(得分:3)

Addition Assignment Operator ...

  

使用此运算符与指定:result = result + 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"

答案 3 :(得分: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"
相关问题