Home >Web Front-end >JS Tutorial >How to Replicate 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?
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; };
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!