I want to iterate through an array of functions, passing each of them some parameters.
let board;
let hand;
const HandCheckers = [
CheckForRoyalFlush(board, hand),
CheckForStraightFlush(board, hand),
CheckForQuads(board, hand),
CheckForFullHouse(board, hand),
CheckForFlush(board, hand),
CheckForTrips(board, hand),
CheckForPairs(board, hand),
CheckForHighCard(board, hand),
];
for (let x = 0; x < HandCheckers.length; x ++) {
HandCheckers[x](board, hand);
}
However, this code fails, giving me the following problem: ReferenceError: board is not defined
How can i call functions like this from an array with parameters?
Cheers!
3 Answers 3
Right now you are executing the functions when you declare them in the array. If you want to just store a function for later execution in the array, leave off the (). If you wanted the function to execute with the value of board and hand at the time it was placed in the array rather than when your iterating over the array use:
let HandCheckers = [
CheckForRoyalFlush.bind(null, board, hand)
];
HandCheckers[0]();
If you want to iterate through an array of functions and pass in parameters, then only store the function reference. Then call them with parameters as you are doing:
let board;
let hand;
const HandCheckers = [
CheckForRoyalFlush,
CheckForStraightFlush,
/* ... */
]
// or use `HandCheckers.forEach(f => f(board, hand))`
for (let x = 0; x < HandCheckers.length; x ++) {
HandCheckers[x](board, hand);
}
Comments
Try this:
let board = 7;
let hand = 2;
const HandCheckers = [
function CheckForRoyalFlush(board, hand){return board+hand},
function CheckForStraightFlush(board, hand){return board*hand}
];
for (let x = 0; x < HandCheckers.length; x ++) {
console.log(HandCheckers[x](board, hand));
};
HandCheckersarray. The error tells exactly that - you're referring a variable that is not defined.boardandhandwere not defined in either case. What exactly are you trying to achieve?const HandCheckers = [ CheckForRoyalFlush(board, hand), CheckForStraightFlush(board, hand), ... ];try just giving a reference, then you can call it in your for statement by passing in board and handconst HandCheckers = [ CheckForRoyalFlush, CheckForStraightFlush, ... ];