简体   繁体   中英

How to create an array filled any number of empty arrays in JavaScript?

Per the title, I'm trying to create an array that is filled with any number of empty arrays in JavaScript.

As an example, let's say I wanted to create an array filled with 9 empty arrays. I could do something like this, which works, but looks quite bad:

let myArray = [[], [], [], [], [], [], [], [], []];

I tried using the fill method, but if I push to any of the empty arrays, the other arrays get filled as well:

let myArray = Array(9).fill([]);

myArray[0].push(1);
// Output = [[1], [1], [1], [1], [1], [1], [1], [1], [1]];

Is there a better way to do this? Perhaps a nice one-liner?

Fill it with Array.fill , then map over each item:

 let myArray = Array(9).fill().map(e => []) myArray[0].push(1); console.log(myArray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM