Why does summing 2 arrays joins everything in a string, concatenating the first and last values:
let array = [1, 2]
let array2 = [3, 4]
let array3 = array array2
console.log(array3) // 1,23,4
CodePudding user response:
That's just how JavaScript works. Both are objects, there's not a defined thing for
between an Array and an Array, so it does the default thing of converting to String and concatenating them (still as a String).
Use the Array.prototype.concat
method to acheive your goal.
let array = [1, 2]
let array2 = [3, 4]
let array3 = array.concat(array2);
console.log(array3) // [1, 2, 3, 4]
Alternatively, you can use the spread operator:
let array = [1, 2]
let array2 = [3, 4]
let array3 = [...array, ...array2];
console.log(array3) // [1, 2, 3, 4]
CodePudding user response:
Because the
operator acts diffently according to the type of the given operands.
- If both operands are numbers, then a sum if performed.
- If one of the operand is not number, then both operands are transformed into string (using .toString) and concatenated.
In your example you may notice that:
array array2 == array.toString() array2.toString()
For further information you may read the docs and the spec
CodePudding user response:
Javascript tries to be smart and figure out what you are trying to do. An addition sign implies adding two strings, so Javascript goes ahead and converts the arrays to strings first for you. How nice, right?
What you want to do is implement the concat method:
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2)