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

How to Replicate Array Elements in JavaScript?

DDD
DDDOriginal
2024-10-24 01:55:29292browse

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;
};

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>

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!

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