Home >Web Front-end >JS Tutorial >How Can I Add Elements to the End of a JavaScript Array?

How Can I Add Elements to the End of a JavaScript Array?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 12:59:26897browse

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:

  • ...item: One or more values to append to the array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn