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
Release: 2024-12-17 12:59:26
Original
904 people have browsed it

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, ...);
Copy after login

Arguments:

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

Example:

Consider the following array:

const arr = ['a', 'b', 'c'];
Copy after login

To append the value 'd' to the end of this array, we can use:

arr.push('d');
Copy after login

The resulting array would now be:

[ 'a', 'b', 'c', 'd' ]
Copy after login

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'];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template