How to add same elements to javascript array n times

前端 未结 3 2118
陌清茗
陌清茗 2020-11-22 08:40
var fruits = [];
fruits.push(\"lemon\", \"lemon\", \"lemon\", \"lemon\");

Instead of pushing same elements how can write it once like this:

<
3条回答
  •  逝去的感伤
    2020-11-22 09:39

    You shouldn't use the array constructor, use [] instead.

    const myArray = [];   // declare array
    
    myArray.length = 5; // set array size
    myArray.fill('foo'); // fill array with any value
    
    console.log(myArray); // log it to the console

提交回复
热议问题