Home  >  Article  >  Web Front-end  >  How to Efficiently Add the Same Element Multiple Times to a JavaScript Array?

How to Efficiently Add the Same Element Multiple Times to a JavaScript Array?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 01:49:04735browse

How to Efficiently Add the Same Element Multiple Times to a JavaScript Array?

Achieving Redundancy in JavaScript Arrays Made Simple

Adding the same element multiple times to a JavaScript array can be a tedious and repetitive task. Instead of repeatedly using the push method like:

var fruits = [];
fruits.push("apple", "apple", "apple", "apple");

This article presents a more efficient solution to add the same element multiple times to an array in a single line of code.

Introducing the fill Method

For primitive data types like strings, numbers, and booleans, JavaScript provides the fill method. This method allows you to fill an array with a specified value for a specified number of times.

Syntax:

array.fill(value, start, end)
  • value: The value to fill the array with.
  • start: The starting index for filling the array (optional, default is 0).
  • end: The ending index for filling the array (optional, default is the length of the array).

Example:

To add the string "lemon" to the array fruits four times, you can use the following code:

var fruits = new Array(4).fill("lemon");
console.log(fruits);

This code will output an array containing the value "lemon" four times:

["lemon", "lemon", "lemon", "lemon"]

By leveraging the fill method, you can add the same element to an array multiple times with ease, optimizing your code and enhancing its readability.

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