.concat()
creates a new array and returns it. It does not add elements onto an existing array.
From MDN:
concat creates a new array consisting of the elements in the object on
which it is called, followed in order by, for each argument, the
elements of that argument (if the argument is an array) or the
argument itself (if the argument is not an array).
concat does not alter this or any of the arrays provided as arguments
but instead returns a shallow copy that contains copies of the same
elements combined from the original arrays. Elements of the original
arrays are copied into the new array as follows:
You can add elements onto an existing array with .splice()
or with .push()
.
var greetings2 = ["affirmative","yeah"];
var obArray2 = ["huh?"];
obArray2.push.apply(obArray2, greetings2);
// display result in snippet
document.write(JSON.stringify(obArray2));
Or, just use the newly returned array from .concat()
:
var greetings2 = ["affirmative","yeah"];
var obArray2 = ["huh?"];
var newArray = obArray2.concat(greetings2);
// display result in snippet
document.write(JSON.stringify(newArray));