"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Create an Array with Elements Repeated Multiple Times in JavaScript?

How to Create an Array with Elements Repeated Multiple Times in JavaScript?

Published on 2024-11-08
Browse:178

How to Create an Array with Elements Repeated Multiple Times in JavaScript?

Creating an Array with Elements Repeated Multiple Times

In JavaScript, creating an array with the same element repeated multiple times can be achieved through various methods.

One straightforward approach is to utilize a for loop and incrementally append the element to the array:

var repeatelem = function(elem, n) {
  var arr = [];
  for (var i = 0; i 

However, in ES6, there's a more concise and efficient way to do this using the Array.fill() method:

ES6 Solution:

console.log(
  Array(5).fill(2)
)
//=> [2, 2, 2, 2, 2]

The Array.fill() method takes two arguments: the element to repeat and the number of times to repeat it. This method is not only more concise but also more performant than the for loop approach, especially for large arrays.

Release Statement This article is reprinted at: 1729683690 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3