Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-23 20:03:30
Original
929 people have browsed it

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

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

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!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!