Skip to content Skip to sidebar Skip to footer

Nested 'for' Loop - Array Undefined

I am working on a JS where I want to create a simple game that starts by chosing number of players, name of each player and whether a player is a dealer or not. There can be only o

Solution 1:

The bug you're specifically asking about appears to me to be that you're iterating over undefined array values, as the error you're getting suggests.

You're getting the number of players you want in line

var playerNumber = prompt('Nr of players?');

Then, you proceed to have two iterations (one nested in the other), in which the inner loop is trying to access values that haven't yet been assigned since the outer loop hasn't gotten there yet:

for (i = 0; i < playerNumber; i++) {
    playersArray[i] = new player(inputName, inputDealer);
    for (k=0; k < playerNumber; k++) {
        if (playersArray[k].playerDealer == 'yes') {
            ...
        }
    }
}

It appears to me that the logical error here is the nested loop. I recommend just initializing all players in one loop, then verify that all players have an assigned dealer afterward.

I should add that I'm being intentionally myopic here and focusing very narrowly on the question asked and overlooking other issues I see.

Solution 2:

Your for loop inside a for loop is iterating over an array that hasn't been filled yet.

First iteration playersArray[j] = new Player(...) makes the array [Player] or an array of one element! Yet the second loop is looking for an array of many elements. once you look for playersArray[1] but there is only playerArray[0] you get undefined and so undefined.playerDealer causes a TypeError.

Solution 3:

`This is your structure stipped-down:

for (i = 0; i < playerNumber; i++) {
   playersArray[i] = newplayer(inputName, inputDealer);
   for (k=0;k<playerNumber;k++)...{

       //anything with index k > i is undefined, since your outer loop//hasn't initialized it yet.
   }
}

It seems that your i-loop is trying to insert elements for the size of the array to be, but your k-loop is trying to also access the entire array instead of just the initialized portions. Limit this to for (k=0; k<i+1 ;k++) so you only check the previously initialized values of you playersArray

Post a Comment for "Nested 'for' Loop - Array Undefined"