Ivelin
Ivelin

Reputation: 159

How to push data to a different array every time with a loop?

I have some data that I'm pushing to an array.

I want to have a loop and each time to push the data to a different array.

Let's say first array is player1, second array should be player2

etc. I only need 2 players now.

But i'm just curious how do I do this with as many players as I want.

I'm trying to make a chess game. Here's how my code looks so far:

function Figuri() {
  this.player1 = [];
  this.player2 = [];
  figurkiNames.forEach(function(figura) {
  });
  for (var y = 1; y <= 2; y++) {
    for (var i = 0; i < 8; i++) {
      this.player1.push(new Figurka(i, figurkiNames[i], y, i+1, 8))
    }
    for (var i = 8; i < 16; i++) {
      this.player1.push(new Figurka(i, "peshka", y, i-7, 7))
    }
  }
}

When y is 1 I need to push to array: "player1". When y is 2 I need to push to array: "player2" etc. And maybe I can have 100 players if i want to.

How do I do this in JavaScript?

Upvotes: 1

Views: 205

Answers (3)

Vladu Ionut
Vladu Ionut

Reputation: 8193

// Code goes here

function Figuri() {
  var players = [],
    playerCount = 10;
  for (var i = 0; i < playerCount; i++)
    players[i] = [];

  figurkiNames.forEach(function(figura) {});
  for (var y = 0; y < playerCount; y++) {
    var currentPlayer = players[y];

    for (var i = 0; i < 8; i++) {
      currentPlayer.push(new Figurka(i, figurkiNames[i], y, i + 1, 8))
    }
    for (var i = 8; i < 16; i++) {
      currentPlayer.push(new Figurka(i, "peshka", y, i - 7, 7))
    }
  }
}

Upvotes: 0

prashant
prashant

Reputation: 1445

Create all the player objects you want and a mapping between the index of y and each player object.

`

var map = new Object(); 
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

`

Above is an example of creating a map....once your map is created when you can select values from your map based on the value of y in your loop.

map[y].push(...)

Upvotes: 0

Brett Green
Brett Green

Reputation: 3755

You'll need a dymamic list of players, and then it's pretty straightforward.

function Figuri() {
  var playerCount = 50;
  this.players = [];
  for (var p=0; p<playerCount; p++){
    players.push(new Player());
  }
  figurkiNames.forEach(function(figura) {
  });
  for (var y = 1; y <= 2; y++) {
    for (var i = 0; i < 8; i++) {
      this.players[y].push(new Figurka(i, figurkiNames[i], y, i+1, 8))
    }
    for (var i = 8; i < 16; i++) {
      this.players[y].push(new Figurka(i, "peshka", y, i-7, 7))
    }
  }
}

Upvotes: 3

Related Questions