C Cezar C Cezar - 1 year ago 86
Javascript Question

Uncaught TypeError inside for loop

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

that increments an object variable.

Inside a
loop, when I call
I get the following error:

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

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
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
at the
part, I get a 2, but
doesn't exist, so I think that is the problem, but I do not know for sure or how to fix it.

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download