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>
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>
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!