2

I am wondering how to make an array with functions and then randomizing one and call it. Here is an example of what I have tested.

functions = [f1(), f2(), f3(), f4()];
rand = functions[Math.floor(Math.random() * functions.length)];

$('p').click(function() {
  rand[0]();
}

I have searched and tried multiple supposed solutions but none of them worked(including this one: Javascript Array of Functions).

2 Answers 2

5

Create the array using function references, and then use the random key generation in the click handler

function log(func) {
  $('#x').html(func)
}

function f1() {
  log('f1')
}

function f2() {
  log('f2')
}

function f3() {
  log('f3')
}

function f4() {
  log('f4')
}

functions = [f1, f2, f3, f4];

$('p').click(function() {
  var rand = functions[Math.floor(Math.random() * functions.length)];
  rand();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="x"></div>
<p>Click</p>

Sign up to request clarification or add additional context in comments.

2 Comments

May I ask what the point of the log function and x div is? Tried it without them and it works great. Thanks btw.
@ItsNotAbyss that was just to demonstrate that the functions are getting called... like when f1 is called the div's text is changed to f1 etc
0
  1. By adding a () after the function names( f1() ), you are effectively executing the function. You must pass a reference of the function to the array so that you can invoke it later. So,

    functions = [f1(), f2(), f3(), f4()];
    

    becomes

    functions = [f1, f2, f3, f4];
    
  2. You seem to be calculating rand only once, because it is not placed in the click event. Include this,

    rand = functions[Math.floor(Math.random() * functions.length)];
    

    in your event handler.

  3. rand is not an array. It contains a reference of one function, which can be invoked by calling it, like this :

    rand();
    

Your full code, along with some additions has been fiddled here : http://jsfiddle.net/sq623mrc/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.