Home > Article > Web Front-end > 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)
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!