Declaring array of objects

前端 未结 15 1427
遇见更好的自我
遇见更好的自我 2020-12-02 07:01

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.



        
15条回答
  •  Happy的楠姐
    2020-12-02 07:44

    You can use fill().

    let arr = new Array(5).fill('lol');
    
    let arr2 = new Array(5).fill({ test: 'a' });
    // or if you want different objects
    let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));
    

    Will create an array of 5 items. Then you can use forEach for example.

    arr.forEach(str => console.log(str));
    

    Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.

提交回复
热议问题