简体   繁体   English

用参数执行数组中的函数

[英]Execute functions in array with parameters

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 但是,此代码失败,给我以下问题: ReferenceError:未定义板

How can i call functions like this from an array with parameters? 我如何从带有参数的数组中调用这样的函数?

Cheers! 干杯!

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: 如果您希望函数在放置到数组中时而不是在遍历数组时使用board和hand的值执行,请使用:

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);
}

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));  
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM