Rob Campbell
Rob Campbell

Reputation: 63

variable incrementing returns NaN

I am attempting to create an app in Javascript/HTML/CSS to run board games, so I can teacher my 11th and 12th grades students to do the same. Mostly I've got it working, including a dice roll, but I have a counter that determines whose turn it is that is returning NaN for one of the turns. It does return all other turns, but adds in the NaN as well.

I'm not using a for() loop because it is inside a given function that starts a player turn. All of the answers I've found online and here at StackOverflow refer to issues in counters using the for() loop.

Here's my code:

var p1="Name1";
var p2="Name2";
var p3="Name3";
var playerList=new Array(p1, p2, p3);

var pTurn=0;
var currentPlayer=playerList[pTurn];

function nextPlayer() {
    pTurn++;
    if(pTurn<playerList.length) {
        pTurn=0;
    }
    currentPlayer=playerList[pTurn];
  /* the rest of the function sends the data to the html page and works */
  }

Upvotes: 0

Views: 249

Answers (1)

Paul Roub
Paul Roub

Reputation: 36438

You need to reset pTurn when it is too large for the list. That is:

if (pTurn >= playerList.length) {
  pTurn = 0;
}

var p1 = "Name1";
var p2 = "Name2";
var p3 = "Name3";
var playerList = new Array(p1, p2, p3);

var pTurn = 0;
var currentPlayer = playerList[pTurn];

function nextPlayer() {
  pTurn++;
  if (pTurn >= playerList.length) {
    pTurn = 0;
  }
  currentPlayer = playerList[pTurn];
}

for (var i = 0; i < 10; ++i) {
  console.log(currentPlayer);
  nextPlayer();
}

Upvotes: 1

Related Questions