随机运行函数

Rez*_*eza -5 javascript arrays jquery

我有一个包含一些函数的数组,它看起来像这样:

var all_questions = [
    show_question(1, 1),
    show_question(2, 1),
    show_question(3, 1),
];
Run Code Online (Sandbox Code Playgroud)

我想随机将这些函数运行到该数组中.我怎样才能做到这一点?

Ror*_*san 6

首先,您需要将这些函数包装在匿名函数中,否则将立即调用它们.从那里你可以从数组中获取一个随机元素并调用它,如下所示:

var all_questions = [
    function() { show_question(1, 1) },
    function() { show_question(2, 1) },
    function() { show_question(3, 1) },
];

all_questions[Math.floor(Math.random() * all_questions.length)]();

function show_question(a, b) {
  console.log(a, b);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您可以通过仅随机化函数的第一个参数来改进逻辑,而不是将函数引用存储在数组中:

function show_question(a, b) {
  console.log(a, b);
}

var rnd = Math.floor(Math.random() * 3) + 1;
show_question(rnd, 1);
Run Code Online (Sandbox Code Playgroud)