Home  >  Article  >  Web Front-end  >  How to Replicate Array Elements Like in Python in JavaScript?

How to Replicate Array Elements Like in Python in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 04:05:30927browse

How to Replicate Array Elements Like in Python in JavaScript?

Replicating Elements in Arrays: An Alternative Approach in JavaScript

In Python, the code [2] * 5 generates an array [2, 2, 2, 2, 2] by repeating the list [2] multiple times. JavaScript arrays, however, do not have this direct replication feature.

Custom Function for Repetition

A straightforward approach in JavaScript is to employ a custom function, such as repeatelem:

<code class="javascript">const repeatelem = (elem, n) => {
  const arr = [];
  for (let i = 0; i <= n; i++) {
    arr.concat(elem);
  }
  return arr;
};</code>

Shorter and Efficient Method

However, in ES6, there is a more efficient method to create arrays with repeated elements:

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

The Array.fill() method returns an array of a specified length, and the array elements are filled with the provided value. Here, we pass the desired length (5) and the element to be repeated (2). This concise solution offers both readability and performance benefits.

The above is the detailed content of How to Replicate Array Elements Like in Python 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