Home >Web Front-end >JS Tutorial >How Can I Efficiently Add Multiple Identical Elements to a JavaScript Array?
Adding Multiple Elements to a JavaScript Array
The Javascript fruits array is populated with four instances of the string "lemon" using multiple push() operations. To achieve the same result with a single expression, we can utilize the following techniques:
For Primitive Data Types (like strings):
If the elements being added to the array are primitive data types (e.g., strings, numbers, booleans), we can use the .fill() method to assign the same value to all elements at once.
var fruits = new Array(4).fill('Lemon'); console.log(fruits);
This code snippet will create an array of length 4 and fill all its elements with the string "Lemon". The result will be:
["Lemon", "Lemon", "Lemon", "Lemon"]
The above is the detailed content of How Can I Efficiently Add Multiple Identical Elements to a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!