Struggle with Andres
Struggle with Andres

Reputation: 17

JavaScript: Calling functions from an Array

I have followed the answer to a previous question but I am not getting the results. I am generating a random number and based on the number, I want to call 1 of four functions:

var functionArray[single, double, triple, quadruple];

function main() {
    ranNum = Math.floor(Math.random() * functionArray.length);
    x = functionArray[ranNum](); /* is this the way to call the function? */
}

/* example of one function in the array */
function single() {
    /* do stuff */
    return x;
}

Upvotes: 0

Views: 70

Answers (1)

Tim
Tim

Reputation: 5681

You are initializing the array wrong:

var functionArray[single, double, triple, quadruple];

Should be:

var functionArray = [single, double, triple, quadruple];

Then it should work!


x = functionArray[ranNum](); 

is this the way to call the function?

Yes, you can call it this way. But it might be more clear if you just execute Function.prototype.call:

x = functionArray[ranNum].call();

Also note that you are using reserved words, like double. You are better off avoiding these.

Upvotes: 7

Related Questions