Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Заполнить пустой массив объектами (https://javascript.ru/forum/misc/85592-zapolnit-pustojj-massiv-obektami.html)

firep91613 03.11.2023 19:39

Заполнить пустой массив объектами
 
this.capacity = capacity;
this.buffer = new Array(capacity);

for (var i = 0; i < this.buffer.length; i++) {
	this.buffer[i] = new LinkedList();
}


Как сделать без for? Я пробовал map и forEach, но чет массив получался пустым...

рони 03.11.2023 19:44

firep91613,
this.buffer = Array.from({length : capacity} , _ => new LinkedList());

firep91613 03.11.2023 19:46

рони,
спасибо!

ksa 03.11.2023 20:14

Цитата:

Сообщение от firep91613
Как сделать без for?

Или так
this.buffer = Array(capacity).fill(new LinkedList());

firep91613 03.11.2023 20:22

ksa,
так будут ссылки на один и тот же объект. Нужно, чтобы все разные были.

ruslan_mart 03.11.2023 20:45

this.buffer = Array.from(Array(capacity), () => new LinkedList());


this.buffer = [...Array(capacity)].map(() => new LinkedList);

firep91613 04.11.2023 11:30

ruslan_mart,
:thanks:


Часовой пояс GMT +3, время: 10:48.