Ref: MDN Documentation
Using apply to append an array to another
You can use
push to append an element to an array. And, because push accepts a variable number of arguments, you can also push multiple elements at once.
But, if you pass an array to
push, it will actually add that array as a single element, instead of adding the elements individually. So you end up with an array inside an array.
What if that is not what you want?
concat does have the desired behaviour in this case, but it does not append to the existing array—it instead creates and returns a new array.
But you wanted to append to the existing array... So what now? Write a loop? Surely not?
apply to the rescue!const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
No comments:
Post a Comment