-5

I have an array that includes some functions and it looks like this:

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

I would like to run those functions into that array randomly. How can I do that?

Reza
  • 513
  • 3
  • 7
  • 20

4 Answers4

6

Firstly you need to wrap those functions in anonymous functions, otherwise they will be called immediately. From there you can get a random element from the array and call it, like this:

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

Note that you could improve the logic by just randomising the first parameter of the function only, instead of storing function references in an array:

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

var rnd = Math.floor(Math.random() * 3) + 1;
show_question(rnd, 1);
Community
  • 1
  • 1
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

If you are calling the same function with different arguments, I would say it's a better option to select the arguments randomly instead of the function.

var args = [
  [1,2],
  [1,3],
  [1,4],
  ...
]

// Get a random element from the array
// http://stackoverflow.com/a/4550514/558021
var randomArgs = args[ Math.floor( Math.random()*args.length) ];

show_question.apply( this, randomArgs );

The apply function is used here because of the way it passes arguments to the target function. When you use apply to execute a function, the arguments you want to pass to the function are provided in an array and then split into individual arguments when passed to the target function.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 2
    You could use `show_question.apply(randomArgs)` and the OP wouldn't need to amend the function at all. – Rory McCrossan Jul 28 '16 at 15:31
  • I considered that but in the end chose this approach as I felt it would better suite the competence level of this question. – Lix Jul 28 '16 at 15:35
  • 1
    I can understand that, although IMO it's better to bring someone up to your level instead of catering to theirs. – Rory McCrossan Jul 28 '16 at 16:05
0

something like

var all_questions = [
    function() show_question(1, 1),
    function() show_question(2, 1),
    function() show_question(3, 1),
];
var x = Math.floor((Math.random() * 3) + 1);
// do something you want
    all_questions[x];
Liam
  • 27,717
  • 28
  • 128
  • 190
brad
  • 993
  • 7
  • 10
0

You can do like this;

var allQuestions = [
                    showQuestion.bind(this, 1, 1),
                    showQuestion.bind(this, 2, 1),
                    showQuestion.bind(this, 3, 1),
                   ],
 displayQuestion = allQuestions[~~(Math.random()*allQuestions.length)];
Redu
  • 25,060
  • 6
  • 56
  • 76