In JavaScript, creating an array with the same element repeated multiple times can be achieved through various methods.
One straightforward approach is to utilize a for loop and incrementally append the element to the array:
var repeatelem = function(elem, n) {
var arr = [];
for (var i = 0; i However, in ES6, there's a more concise and efficient way to do this using the Array.fill() method:
ES6 Solution:
console.log(
Array(5).fill(2)
)
//=> [2, 2, 2, 2, 2]
The Array.fill() method takes two arguments: the element to repeat and the number of times to repeat it. This method is not only more concise but also more performant than the for loop approach, especially for large arrays.
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