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?
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?
It's converting the individual arrays to strings, then combining the strings.
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:
The
+
concats strings, so it converts the arrays to strings.To combine arrays, use
concat
.[1,2]+[3,4]
in JavaScript is same as evaluating:and so to solve your problem, best thing would be to add two arrays in-place or without creating a new array:
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.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.