Home > Web Front-end > JS Tutorial > How to Efficiently Add Multiple Occurrences of an Element to a JavaScript Array?

How to Efficiently Add Multiple Occurrences of an Element to a JavaScript Array?

Linda Hamilton
Release: 2024-11-30 05:33:10
Original
604 people have browsed it

How to Efficiently Add Multiple Occurrences of an Element to a JavaScript Array?

Adding Multiple Occurrences of Elements to a JavaScript Array

When working with arrays in JavaScript, it's sometimes necessary to add the same element multiple times. The traditional approach involves repeatedly pushing the element onto the array using array.push().

Consider the following scenario:

var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");
Copy after login

This code appends the string "lemon" four times to the fruits array. While this method is straightforward, it can become tedious when multiple occurrences are required.

Using Array.fill for Primitives

For primitive data types like strings, JavaScript provides a more efficient way to add multiple elements at once using the array.fill() method. The syntax is:

array.fill(value, start, end)
Copy after login
  • value: The value to be filled in the array.
  • start (optional): The starting index at which to begin filling. Defaults to 0.
  • end (optional): The ending index at which to stop filling. Defaults to the length of the array.

In the case of the fruits array, we can add four occurrences of "lemon" like so:

var fruits = new Array(4).fill('Lemon');
console.log(fruits);
Copy after login

This code creates a new array of length 4 and fills all its elements with the string "Lemon".

Note: Array.fill() is supported for primitive data types only. For objects and other complex data structures, it's recommended to use loops or spread operators.

The above is the detailed content of How to Efficiently Add Multiple Occurrences of an Element to 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