Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-17 01:49:04
Original
733 people have browsed it

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

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

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

["lemon", "lemon", "lemon", "lemon"]
Copy after login

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!

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