skip to Main Content
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


  1. To add additional regions to the player_1.regions array without replacing the existing value, you can use the push() function. Here’s how you can do it:

    player_1.regions.push('land 2');
    player_1.regions.push('land 3');
    

    This code will add the values ‘land 2’ and ‘land 3’ to the player_1.regions array. You can continue using the push() 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 a forEach() function, like so:

    player_1.regions.forEach(function(region) {
      console.log(region);
    });
    
    Login or Signup to reply.
  2. Is that what you wanted?

    function player_factory(name, regions) {
      this.name = name;
      this.regions = [regions];
    }
    
    var player_1 = new player_factory('player 1', 'land 1');
    player_1.regions.push('123')
    console.log(player_1)
    Login or Signup to reply.
  3. 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:

    function player_factory(name, ...regions) {
            this.name = name;
            this.regions = regions.flat();
        }
    
    var player_1 = new player_factory('player 1', 'land 1', 'land 2', ['land 3']);
    player_1.regions.push('land 4', 'land 5');
    
    for(const region of player_1.regions){
      console.log(region);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search