Home > Article > Web Front-end > How to Easily Add the Same Element Multiple Times to a JavaScript Array?
When adding the same element multiple times to a JavaScript array, it's common to use the push method in a repetitive manner. However, this can be tedious and prone to errors. Is there a better way?
The answer lies in utilizing the JavaScript fill method, particularly designed for inserting the same value multiple times into an array. Instead of writing:
var fruits = []; fruits.push("lemon", "lemon", "lemon", "lemon");
You can simplify it to:
var fruits = new Array(4).fill('Lemon');
This syntax creates an array of a specified length (4 in this case) and fills it with the provided value ('Lemon'). The result is an array with four 'Lemon' elements:
["Lemon", "Lemon", "Lemon", "Lemon"]
This method not only simplifies your code but also ensures consistency and reduces the risk of errors. It's a convenient and efficient way to add multiple elements of the same value to an array in JavaScript.
The above is the detailed content of How to Easily Add the Same Element Multiple Times to a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!