Funktion Funktion - 1 month ago 5
Javascript Question

Javascript array not looping back to beginning

I'm writing a simple card game, but for some reason this code below behaves very strangely...The turn functions is first called using

theTurn(0)


players
is an array of objects with player name and hand etc.

function theTurn(playerNumber) {
if(play == 1) {
$('#player').text(players[playerNumber].Name);
$('#submit').click(function() {
nextPlayer(playerNumber);
})
}
}

function nextPlayer(playerNumber) {
if(playerNumber == players.length - 1) {
theTurn(0);
} else {
theTurn(playerNumber + 1);
}
}


For some reason I get player 0 then 1 then 1 again and then 0.

I've left out some of the stuff in theTurn...but this is the gist of it and the problem shows up in this simplified version too.

Any help with my faulty logic would be greatly appreciated.

Answer

This actually makes a little more sense... just add the click handler once, then set the player number as a data property so the nextPlayer function knows what it is without an argument.

$('#player').data('activePlayer', 0);
$('#submit').click(function() {
    nextPlayer();
});

function theTurn(playerNumber) {
    if(play == 1) {
        $('#player').text(players[playerNumber].Name);
        $('#player').data('activePlayer', playerNumber);

    }
}

function nextPlayer() {
    var playerNumber = $('#player').data('activePlayer');

    if(playerNumber == players.length - 1) {
        theTurn(0);
    } else {
        theTurn(playerNumber + 1);
    }
}
Comments