I've gotten a Random Lotto Generator script to work in JavaScript in one game. Now, I'm trying to get it to function for multiple Lotto games and figured Objects were the best way to adjust to the different formats of each game to account for different number pools, different selected numbers, 'bonus balls', duplicate numbers, etc.
const game = [{name: "Lotto Texas", balls: 6, numbers: 54, start: 1, duplicates: false, bonusBall: false, results: []},
{name: "Pick 3", balls: 3, numbers: 10, start: 0, duplicates: true, bonusBall: false, results: []},
{name: "Powerball", balls: 5, numbers: 69, start: 1, duplicates: false, bonusBall: true, bonusNumbers: 26, results: [], bonus: []}];
game.forEach (lottoResults()); // gets results
function lottoResults(){
this.results.length = this.balls; //Here is where the error occurs. This is supposed to assign the balls property to the results array's length value.
if (!this.duplicates){ //checks if duplicates allowed
this.results.forEach(duplicateCheck());
}
else{
this.results.forEach(lottoBall())
}
if(this.bonusBall){
this.bonus.push(lottoBall(this.bonusNumbers, this.start)); //assigns a number to bonus ball
}
}
I'm trying to set a blank array initialized in each object, with the amount with the 'balls' property (referring to lotto balls) setting how big the array is dependent on the game. However, anytime I try to set that up, I keep getting an Uncaught TypeError: Undefined is not a function. I've tried setting the object property value to a primitive variable, establishing the array length within the initialized object variables, but still get the same error in some form. Am I just misusing the object and should be calling the values differently?
You are invoking lottoResults here within forEach by placing () after the function name
game.forEach (lottoResults());
Instead, you should pass the function like this
game.forEach (lottoResults);
ref: https://www.w3schools.com/jsref/jsref_foreach.asp
Note: Same thing applies to duplicateCheck and lottoBall passed to forEach, remove the ()