Home >Web Front-end >JS Tutorial >How Can I Add Elements to the End of a JavaScript Array?
Appending Elements to Arrays in JavaScript
When working with arrays, it's often necessary to add new elements to them. In JavaScript, the Array.prototype.push method provides a simple and efficient way to append values to the end of an array.
Syntax:
arr.push(...item1, item2, ...);
Arguments:
Example:
Consider the following array:
const arr = ['a', 'b', 'c'];
To append the value 'd' to the end of this array, we can use:
arr.push('d');
The resulting array would now be:
[ 'a', 'b', 'c', 'd' ]
Note: The push method modifies the original array in-place. If you need an immutable copy of the array with the new element appended, you can use the spread operator to create a new array:
const newArr = [...arr, 'd'];
The above is the detailed content of How Can I Add Elements to the End of a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!