Home > Web Front-end > JS Tutorial > How Can I Efficiently Add Multiple Identical Elements to a JavaScript Array?

How Can I Efficiently Add Multiple Identical Elements to a JavaScript Array?

Mary-Kate Olsen
Release: 2024-11-17 17:12:02
Original
772 people have browsed it

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

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

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!

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