1

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?

2
  • 1
    Save all the players in an array or object as well? The length will then tell you how many players you have. Commented Dec 29, 2016 at 13:51
  • Thank you all for the answers. Commented Dec 31, 2016 at 10:27

3 Answers 3

3

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))
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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(...)

Comments

0
// 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))
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.