ItsNotAbyss
ItsNotAbyss

Reputation: 345

Javascript function array

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).

Upvotes: 2

Views: 160

Answers (2)

krishwader
krishwader

Reputation: 11371

  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/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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>

Upvotes: 5

Related Questions