我想将一个数组的元素添加到另一个数组中,所以我尝试了这样做:
[1,2] + [3,4]
它的答复是:
"1,23,4"
这是怎么回事?
我想将一个数组的元素添加到另一个数组中,所以我尝试了这样做:
[1,2] + [3,4]
它的答复是:
"1,23,4"
这是怎么回事?
当前回答
从ES6开始,我们可以使用展开运算符做类似的事情:
[...[1, 2], ...[3, 4]]
给:
[1, 2, 3, 4]
它也适用于命名变量:
const a = [1, 2];
const b = [3, 4];
const array = [...a, ...b];
给出相同的结果。
其他回答
另一个使用简单的“+”符号的结果是:
[1,2]+','+[3,4] === [1,2,3,4]
所以像这样的东西应该工作(但是!):
var a=[1,2];
var b=[3,4];
a=a+','+b; // [1,2,3,4]
... 但它会将变量a从数组转换为字符串!记住这一点。
在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];
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]
从ES6开始,我们可以使用展开运算符做类似的事情:
[...[1, 2], ...[3, 4]]
给:
[1, 2, 3, 4]
它也适用于命名变量:
const a = [1, 2];
const b = [3, 4];
const array = [...a, ...b];
给出相同的结果。
+连接字符串,因此它将数组转换为字符串。
[1,2] + [3,4]
'1,2' + '3,4'
1,23,4
要组合数组,使用concat。
[1,2].concat([3,4])
[1,2,3,4]