function player_factory(name, regions) {
this.name = name;
this.regions = regions;
}
var player_1 = new player_factory('player 1', 'land 1');
I would like to add additional regions to player_1.regions like you do with an array using the push function and I would like to be able to loop through the values, not replace the one value that it stores.
3
Answers
To add additional regions to the
player_1.regions
array without replacing the existing value, you can use thepush()
function. Here’s how you can do it:This code will add the values ‘land 2’ and ‘land 3’ to the
player_1.regions
array. You can continue using thepush()
function to add more regions as needed. To loop through the values in the player_1.regions array, you can use a loop such as a for loop or aforEach()
function, like so:Is that what you wanted?
You can use argument spread syntax and
Array::flat()
to provide regions in any form in the constructor and having them as an array in the end: