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

How to Replicate Array Elements Like in Python in JavaScript?

Mary-Kate Olsen
Release: 2024-10-24 04:05:30
Original
1008 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template