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");
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)
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);
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!