我想遍历一系列函数,并为每个函数传递一些参数。
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);
}
但是,此代码失败,给我以下问题: ReferenceError:未定义板
如何从带有参数的数组中调用类似的函数?
干杯!
答案 0 :(得分:4)
现在,当您在数组中声明函数时,它们正在执行。如果只想存储一个函数供以后在数组中执行,请不要使用()。如果您希望函数在放置到数组中时而不是在遍历数组时使用board和hand的值执行,请使用:
let HandCheckers = [
CheckForRoyalFlush.bind(null, board, hand)
];
HandCheckers[0]();
答案 1 :(得分:1)
如果要遍历函数数组并传入参数,则仅存储函数引用。然后在执行操作时使用参数调用它们:
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);
}
答案 2 :(得分:0)
尝试一下:
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));
};