[Javascript] JavaScript Array Methods in Depth - push

时间:2023-03-09 03:56:46
[Javascript] JavaScript Array Methods in Depth - push

Array push is used to add elements to the end of an Array. In this lesson we'll see how the push method accepts multiple arguments, can be used to merge two arrays,.

Push can accept multi args:

const pets = ["dog", "hamster"];
pets.push("cat");
console.log(pets); //["dog", "hamster", "cat"] pets.push("brid", "horse");
console.log(pets); //["dog", "hamster", "cat", "brid", "horse"]

Push can merge two arrays:

const pets = ["dog", "hamster"];
const pets2 = ["Hamster", "cat"];
pets.push.apply(pets, pets2);
console.log(pets); //["dog", "hamster", "Hamster", "cat"]