Lucas T.
Lucas T.

Reputation: 406

Declared array returning undefined

In my project, one of the functions should update a list of users with new stats,and I have that function:

function gameEnded(team){
    //reset variables
    playersObject = {};

    isPlaying = false;
    subQueue = {};
    subArray = [];
    blueList = ["Jonas","LucasTT"];
    redList = ["Lucas","Manelzao"];
    //updates database
    for(i=0; i<blueList.length; i++){
        getPlayerStats(blueList[i], function(oldStats){
            console.log(blueList[i]);
            setPlayerStats(blueList[i], [oldStats[0]+6,oldStats[1]]);
        });
    }
}

It should get the a name from the list, get the name's stats(using MySQL),and then update it. But, the console.log there is logging undefined, but the array is declared. What is causing that to do so?

Upvotes: 1

Views: 1380

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17505

The problem is that the callback doesn't run until after that loop has finished, at which point i is equal to blueList.length, and in javascript indexing past the end of an array returns undefined.

You'll want to freeze the value of i in each iteration of the loop, which can be done with an IIFE:

for(i=0; i<blueList.length; i++){
    (function(i) {
        getPlayerStats(blueList[i], function(oldStats){
            console.log(blueList[i]);
            setPlayerStats(blueList[i], [oldStats[0]+6,oldStats[1]]);
        });
    })(i);
}

Upvotes: 1

Related Questions