0

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;
}
2
  • 1
    what is your problem here with the code Commented Mar 30, 2016 at 15:26
  • 1
    var functionArray=[single, double, triple, quadruple]; Commented Mar 30, 2016 at 15:30

1 Answer 1

7

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.

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

2 Comments

Very much appreciated!
@StrugglewithAndres You can accept this answer if it fits your needs! :)

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.