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

2019-01-01 14:33发布

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"

What is going on?

13条回答
梦该遗忘
2楼-- · 2019-01-01 14:38

It's converting the individual arrays to strings, then combining the strings.

查看更多
伤终究还是伤i
3楼-- · 2019-01-01 14:39

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].

Assuming both arrays have the same arity/length, here is one simple solution:

const arr1 = [1, 2];
const arr2 = [3, 4];

const add = (a1, a2) => a1.map((e, i) => e + a2[i]);

console.log(add(arr1, arr2)); // ==> [4, 6]

查看更多
何处买醉
4楼-- · 2019-01-01 14:41

The + concats strings, so it converts the arrays to strings.

[1,2] + [3,4]
'1,2' + '3,4'
1,23,4

To combine arrays, use concat.

[1,2].concat([3,4])
[1,2,3,4]
查看更多
情到深处是孤独
5楼-- · 2019-01-01 14:48

[1,2]+[3,4] in JavaScript is same as evaluating:

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

and so to solve your problem, best thing would be to add two arrays in-place or without creating a new array:

var a=[1,2];
var b=[3,4];
a.push.apply(a, b);
查看更多
永恒的永恒
6楼-- · 2019-01-01 14:52

It adds the two arrays as if they were strings.

The string representation for the first array would be "1,2" and the second would be "3,4". So when the + sign is found, it cannot sum arrays and then concatenate them as being strings.

查看更多
刘海飞了
7楼-- · 2019-01-01 14:52

It looks like JavaScript is turning your arrays into strings and joining them together. If you want to add tuples together, you'll have to use a loop or a map function.

查看更多
登录 后发表回答