Home  >  Article  >  Web Front-end  >  How to Create an Array with Elements Repeated Multiple Times in JavaScript?

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

DDD
DDDOriginal
2024-10-23 20:03:301003browse

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:

<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!

Statement:
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