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

How to Create an Array with Repeated Elements in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 00:14:30728browse

How to Create an Array with Repeated Elements in JavaScript?

An Array of Repeated Elements in JavaScript

Creating an array with the same element repeated multiple times is essential in various programming scenarios. In Python, this can be achieved with list multiplication as seen in [2] * 5. However, this functionality is not directly available in JavaScript's arrays.

Custom Function Approach

To address this need, one approach is to create a custom function, such as the repeatelem function provided in the question. This function accepts an element and a number of repetitions and initializes an empty array. It then iteratively adds the element to the array using the concat method.

ES6 Array.fill() Method

Fortunately, ES6 introduces the Array.fill() method, which provides a more concise solution for this problem. The fill() method fills an array with a provided value, starting at the specified index and extending up to the end of the array. By setting the index to zero and the value to the desired element, we can easily create an array with the element repeated as many times as needed.

Example:

<code class="js">console.log(
  Array(5).fill(2)
);
// Output: [2, 2, 2, 2, 2]</code>

The Array.fill() method simplifies the process of creating arrays with repeated elements, making it a more efficient and readable solution in JavaScript.

The above is the detailed content of How to Create an Array with Repeated Elements 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