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

How to Replicate Array Elements in JavaScript?

DDD
Release: 2024-10-24 01:55:29
Original
199 people have browsed it

How to Replicate Array Elements in JavaScript?

Replicating Array Elements in JavaScript

In Python, multiplying a list by a number replicates its elements that many times. For instance, [2] * 5 yields [2, 2, 2, 2, 2]. Can we replicate this functionality in JavaScript using arrays?

Custom Function

One approach is to define a function like the following:

<code class="javascript">var repeatelem = function(elem, n){
    // returns an array with element elem repeated n times.
    var arr = [];

    for (var i = 0; i <= n; i++) {
        arr = arr.concat(elem);
    };

    return arr;
};
Copy after login

ES6 fill() Method

However, starting with ES6, JavaScript introduced the Array.fill() method, which provides a more concise and efficient solution:

<code class="javascript">console.log(
  Array(5).fill(2)
)
//=> [2, 2, 2, 2, 2]</code>
Copy after login

Here, Array(5) creates an empty array of length 5, and .fill(2) populates it with the provided element (2). This approach is both shorter and faster than the custom function, offering a clean and convenient way to replicate array elements in JavaScript.

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