Home >Web Front-end >JS Tutorial >How Can I Append Elements to an Array in JavaScript?
Appending Elements to Arrays in JavaScript
In JavaScript, arrays are used to store collections of elements. When you need to add new elements to an existing array, there are two common methods:
Array.prototype.push
The most common method to append an element to an array is to use the Array.prototype.push method. This method adds one or more new elements to the end of an array and returns the new length of the array.
// initialize array var arr = [ "Hi", "Hello", "Bonjour" ]; // append new value to the array arr.push("Hola"); console.log(arr); // [ 'Hi', 'Hello', 'Bonjour', 'Hola' ]
Spread Operator
Another way to append an element to an array is to use the spread operator (...). This operator allows you to spread the elements of an existing array into a new array, and then add new elements to the end.
// initialize array var arr = [ "Hi", "Hello", "Bonjour" ]; // append new value to the array using the spread operator var newArr = [...arr, "Hola"]; console.log(newArr); // [ 'Hi', 'Hello', 'Bonjour', 'Hola' ]
Both methods achieve the same result, but the Array.prototype.push method is more convenient when you only need to append a few elements to an array. For more complex manipulations, the spread operator offers greater flexibility.
The above is the detailed content of How Can I Append Elements to an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!