2

I'am trying to fill an array (rooms) with the same object type (room).

This works fine :

var rooms = new Array(10);

for (var i=0; i<10; i++){
  rooms[i] = new room();
}

Isn't there any other method that takes only one line of code to do the same thing?

I've tried :

var rooms = new Array(10).fill(new room());

but each box of the array contains the same object (same reference).

Thanks.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
Mit
  • 339
  • 1
  • 7
  • 23

3 Answers3

1

You should use map method in order to have different objects.

var rooms = new Array(10).fill().map(function(){
   return new room();
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

This will work in (since ES6):

Array(10).fill().map((e,i)=>new room());
Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57
1

Another nice way of doing this would be;

var rooms = Array.from({length:10}, _ => new Room());
rooms[0] === rooms[1] // <- false
Redu
  • 25,060
  • 6
  • 56
  • 76