数组与 + 和 concat 的连接是否不同

Is array concatenation with + and concat different

In this fiddle, When using + operator the delimeter , is skipped, while concat method is not skipping ,.

在javascript中,一般用+操作符的拼接和concat方法是一样的。它不也适用于数组吗?

考虑一下:

[1, 2, 3] + [4, 5, 6] // "1,2,34,5,6"
[1, 2, 3].concat([4, 5, 6]) // [1, 2, 3, 4, 5, 6]

在数组上使用加连接运算符将使数组经历以下步骤:

[1, 2, 3] + [4, 5, 6]
[1, 2, 3].toString() + [4, 5, 6].toString()
"1,2,3" + "4,5,6"
"1,2,34,5,6"

定义加号运算符是为了解决两个目的:

  1. 添加数字。
  2. 加入字符串。

但未定义应用于数组。来自 ECMA section

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.

在数组上使用 +(String concatenation) 运算符时,通过调用 Array 原型上的 toString 方法将数组隐式类型转换为字符串.

要连接两个 数组,请使用 Array#concat 方法。

使用哪一个取决于用例。

  1. 要获得 string 的结果,您可以使用 + operator
  2. 要获得 array 的结果,请使用 concat.

function testing() {
    var alpha = ["a", "b", "c"];
    var numeric = [1, 2, 3];
    var usingPlus = alpha + numeric;
    console.log(typeof usingPlus);

    var usingConcat = alpha.concat(numeric);
    console.log(typeof usingConcat);
};

window.onload = testing;