I'm trying to create an array that keeps track of which lines are already hit so they aren't checked repeatedly if I allow the game to continue until another bingo is hit. This is where my problem is occurring. winningLines is defined outside the function so it's a global variable. I create a new key containing the ID of the bingo card and attached an associative array to it. It then exists until the $.each(bingoLines function occurs. Then it stops working. The console.log lines shows where it works and where it dies.
var winningLines = {};
function setEmptyWinningLines(){
$.each($('.bingoCards'), function(){
winningLines[this.id] = {};
console.log(winningBingoLines[this.id]);//object exists
//Set the individual possibilities from bingoLines array for each card.
$.each(bingoLines[settings['game-type']], function(lineNumber, spotsToHit){
console.log(winningLines[this.id]);//object undefined
//Set each line to false.
winningLines[this.id][lineNumber] = false;//Where the error occurs.
});//end each bingoLines
});//end each
}//end function
The problem I am dealing with is I am getting error message "TypeError: Cannot set properties of undefined (setting '0')". While I understand that javascript doesn't like to set variables unless you specifically tell it to do so but where I included the console.log lines shows where it goes from the object existing to suddenly not existing. The array itself is defined outside of the function so I honestly cannot figure out what is causing it unless it is something I am overlooking. Any help would be appreciated in advance.
Cause
The issue was due to a misunderstanding of how the this
keyword works inside nested $.each
loops. In the inner loop, this refers to the current item in that loop, not the outer loop’s context.
Solution To resolve the issue, I stored the card’s ID in a variable before entering the inner loop. This way, I could correctly reference the current card while setting up the winningLines object.
var winningLines = {};
function setEmptyWinningLines(){
// Loop through each bingo card
$.each($('.bingoCards'), function(){
var cardId = this.id; // Store the current bingo card's ID
winningLines[cardId] = {};
// Loop through each line in the bingoLines array
$.each(bingoLines, function(lineNumber, spotsToHit){
// Set each line to false for the current card
winningLines[cardId][lineNumber] = false;
});
});
}
Explanation I used var cardId = this.id; to store the ID of the current .bingoCards element. Inside the inner loop, I accessed winningLines[cardId] to correctly assign values without encountering the undefined error. This approach ensures that the winningLines object is correctly initialized for each card, and the error is avoided.