An Array of Repeated Elements in JavaScript
Creating an array with the same element repeated multiple times is essential in various programming scenarios. In Python, this can be achieved with list multiplication as seen in [2] * 5. However, this functionality is not directly available in JavaScript's arrays.
Custom Function Approach
To address this need, one approach is to create a custom function, such as the repeatelem function provided in the question. This function accepts an element and a number of repetitions and initializes an empty array. It then iteratively adds the element to the array using the concat method.
ES6 Array.fill() Method
Fortunately, ES6 introduces the Array.fill() method, which provides a more concise solution for this problem. The fill() method fills an array with a provided value, starting at the specified index and extending up to the end of the array. By setting the index to zero and the value to the desired element, we can easily create an array with the element repeated as many times as needed.
Example:
console.log(
Array(5).fill(2)
);
// Output: [2, 2, 2, 2, 2]
The Array.fill() method simplifies the process of creating arrays with repeated elements, making it a more efficient and readable solution in JavaScript.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3