Home > Web Front-end > JS Tutorial > How to Replicate Array Elements Multiple Times in JavaScript without the Multiplication Operator?

How to Replicate Array Elements Multiple Times in JavaScript without the Multiplication Operator?

Susan Sarandon
Release: 2024-10-24 03:01:02
Original
679 people have browsed it

How to Replicate Array Elements Multiple Times in JavaScript without the Multiplication Operator?

Replicating Array Elements Multiple Times in JavaScript: Alternative Approaches

In Python, the multiplication operator can be used to create arrays where each element is repeated multiple times. However, JavaScript requires a more explicit approach to achieve the same result.

Function-Based Implementation

One possible solution is to use a function to repeat elements:

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, in ES6, there is a simpler and more concise method available: Array.fill(). This method takes two parameters: the value to repeat and the number of times it should be repeated.

console.log(
  Array(5).fill(2)
)
//=> [2, 2, 2, 2, 2]
Copy after login

This approach is not only shorter but also more efficient, as it initializes the array with the correct size upfront and then fills it in a single operation.

The above is the detailed content of How to Replicate Array Elements Multiple Times in JavaScript without the Multiplication Operator?. 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