我想将一个数组的元素添加到另一个数组中,所以我尝试了这样做:
[1,2] + [3,4]
它的答复是:
"1,23,4"
这是怎么回事?
我想将一个数组的元素添加到另一个数组中,所以我尝试了这样做:
[1,2] + [3,4]
它的答复是:
"1,23,4"
这是怎么回事?
当前回答
这是因为,+运算符假设操作数是字符串,如果它们不是数字。因此,如果它不是一个数字,它首先将它们转换为字符串和连接,以给出最终结果。此外,它不支持数组。
其他回答
这是因为,+运算符假设操作数是字符串,如果它们不是数字。因此,如果它不是一个数字,它首先将它们转换为字符串和连接,以给出最终结果。此外,它不支持数组。
在JavaScript中,二进制加法运算符(+)既可以执行数字加法,也可以执行字符串连接。然而,当它的第一个参数既不是数字也不是字符串时,它会将其转换为字符串(因此是"1,2"),然后它会对第二个"3,4"进行同样的操作,并将它们连接到"1,23,4"。
尝试使用Arrays的"concat"方法:
var a = [1, 2];
var b = [3, 4];
a.concat(b) ; // => [1, 2, 3, 4];
它像添加字符串一样添加两个数组。
第一个数组的字符串表示形式是“1,2”,第二个数组是“3,4”。因此,当找到+号时,它不能对数组求和,然后将它们作为字符串连接起来。
它将单个数组转换为字符串,然后组合字符串。
JavaScript的+运算符有两个目的:将两个数字相加,或者连接两个字符串。它对数组没有特定的行为,所以它将它们转换为字符串,然后连接它们。
如果你想连接两个数组来生成一个新的数组,请使用.concat方法:
[1, 2].concat([3, 4]) // [1, 2, 3, 4]
如果你想有效地将所有元素从一个数组添加到另一个数组,你需要使用.push方法:
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]
+运算符的行为在ECMA-262 5e章节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: Let lref be the result of evaluating AdditiveExpression. Let lval be GetValue(lref). Let rref be the result of evaluating MultiplicativeExpression. Let rval be GetValue(rref). Let lprim be ToPrimitive(lval). Let rprim be ToPrimitive(rval). If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim) Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.
可以看到每个操作数都被转换为原始数。通过进一步阅读,我们可以发现ToPrimitive总是将数组转换为字符串,从而产生这样的结果。