C Cezar C Cezar - 3 months ago 17
Javascript Question

Uncaught TypeError inside for loop

I have an array of objects (players), and those objects have a method

increment
that increments an object variable.

Inside a
for
loop, when I call
players[x].increment();
I get the following error:


intex.html:56 Uncaught TypeError: Cannot read property 'increment' of
undefined


for (var x = 0; x < players.length; x++) {
$("#button-" + x).click(function() { //I select one of the buttons
players[x].increment(); //Here is the problem
//This part forwards doesn't matter
$("#score-" + x + "-n").text(players[x].score);
if (players[x].score >= 10) {
alert(players[x].name + " WINS!");
$("#alertz").html('<div class="alert alert-info" style="text-align:center;" >' + players[x].name + 'WINS!!!</div>');
};
});
};


When I call for example
players[0].increment();
outside the loop, I do not have any problem.

In case it isn't clear. I have a simple page with two buttons. Based on what button I press, it increments, and display a variable.

When I use
console.log(var)
at the
increment
part, I get a 2, but
players[2]
doesn't exist, so I think that is the problem, but I do not know for sure or how to fix it.

Answer

Your iterator is equal to players.length when the click event is fired, and the click handler then uses that iterator in an attempt to access an index that is out of range for your players array.

Try putting an index attribute on your button like this instead:

<button class="player-button" data-player-index="0">Increment</button>
<button class="player-button" data-player-index="1">Increment</button>

$('.player-button').click(function() {
    var index = $this.attr('data-player-index');
    players[index].increment();
});