Use the push() function to append to an array:
If you're only appending a single variable, then
push()works just fine. If we need to append another array, use
Will spit out:
The concat does not affect
ar2 unless reassigned, for example:
- WE think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
As a result of this we can use push.apply to append an array to another array like so:
Annotated ES5 has more info on exactly what push and apply do.
2016 update: with spread , we don't need that
apply anymore, like:
We can use
apply function to append two arrays.
It will append array2 to array1. Now
[11, 32, 75, 99, 67, 34]. This code is much simpler than writing
for loops to copy each and every items in the array.
a now contains all the elements, [1, 2, 3, 3, 4, 5].