Home > Article > Web Front-end > How to Create an Array with Elements Repeated Multiple Times in JavaScript?
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:
<code class="javascript">var repeatelem = function(elem, n) { var arr = []; for (var i = 0; i < n; i++) { arr.push(elem); } return arr; };
However, in ES6, there's a more concise and efficient way to do this using the Array.fill() method:
ES6 Solution:
<code class="javascript">console.log( Array(5).fill(2) ) //=> [2, 2, 2, 2, 2]</code>
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.
The above is the detailed content of How to Create an Array with Elements Repeated Multiple Times in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!