Why is [1,2] + [3,4] = “1,23,4” in JavaScript?

前端 未结 13 1499
小蘑菇
小蘑菇 2020-11-22 16:56

I wanted to add the elements of an array into another, so I tried this:

[1,2] + [3,4]

It responded with:

\"1,23,4\"
         


        
相关标签:
13条回答
  • 2020-11-22 17:49

    JavaScript's + operator has two purposes: adding two numbers, or joining two strings. It doesn't have a specific behaviour for arrays, so it's converting them to strings and then joining them.

    If you want to join two arrays to produce a new one, use the .concat method instead:

    [1, 2].concat([3, 4]) // [1, 2, 3, 4]
    

    If you want to efficiently add all elements from one array to another, you need to use the .push method:

    var data = [1, 2];
    
    // ES6+:
    data.push(...[3, 4]);
    // or legacy:
    Array.prototype.push.apply(data, [3, 4]);
    
    // data is now [1, 2, 3, 4]
    

    The behaviour of the + operator is defined in ECMA-262 5e Section 11.6.1:

    11.6.1 The Addition operator ( + )

    The addition operator either performs string concatenation or numeric addition. The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:

    1. Let lref be the result of evaluating AdditiveExpression.
    2. Let lval be GetValue(lref).
    3. Let rref be the result of evaluating MultiplicativeExpression.
    4. Let rval be GetValue(rref).
    5. Let lprim be ToPrimitive(lval).
    6. Let rprim be ToPrimitive(rval).
    7. If Type(lprim) is String or Type(rprim) is String, then
      1. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
    8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.

    You can see that each operand is converted ToPrimitive. By reading further we can find that ToPrimitive will always convert arrays to strings, producing this result.

    0 讨论(0)
提交回复
热议问题