我想将一个数组的元素添加到另一个数组中,所以我尝试了这样做:

[1,2] + [3,4]

它的答复是:

"1,23,4"

这是怎么回事?


当前回答

[1,2]+[3,4]在JavaScript中等同于求值:

new Array( [1,2] ).toString() + new Array( [3,4] ).toString();

所以为了解决你的问题,最好的方法是在原地添加两个数组,或者不创建一个新数组:

var a=[1,2];
var b=[3,4];
a.push.apply(a, b);

其他回答

它像添加字符串一样添加两个数组。

第一个数组的字符串表示形式是“1,2”,第二个数组是“3,4”。因此,当找到+号时,它不能对数组求和,然后将它们作为字符串连接起来。

如果你可以在JavaScript中重载操作符,那就太好了,但你不能: 我可以在Javascript定义自定义操作符重载吗? 你只能破解“==”操作符,它在比较之前转换为字符串: http://blogger.xs4all.nl/peterned/archive/2009/04/01/462517.aspx

这是因为,+运算符假设操作数是字符串,如果它们不是数字。因此,如果它不是一个数字,它首先将它们转换为字符串和连接,以给出最终结果。此外,它不支持数组。

Some answers here have explained how the unexpected undesired output ('1,23,4') happens and some have explained how to obtain what they assume to be the expected desired output ([1,2,3,4]), i.e. array concatenation. However, the nature of the expected desired output is actually somewhat ambiguous because the original question simply states "I wanted to add the elements of an array into another...". That could mean array concatenation but it could also mean tuple addition (e.g. here and here), i.e. adding the scalar values of elements in one array to the scalar values of the corresponding elements in the second, e.g. combining [1,2] and [3,4] to obtain [4,6].

假设两个数组都有相同的arity/length,这里有一个简单的解决方案:

Const arr1 = [1,2]; Const arr2 = [3,4]; Const add = (a1, a2) => a1。Map ((e, i) => e + a2[i]); console.log(添加(arr1 arr2));// ==> [4,6]

看起来JavaScript正在将数组转换为字符串并将它们连接在一起。如果要将元组添加到一起,则必须使用循环或映射函数。