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;
}
asked Mar 30, 2016 at 15:25
Struggle with Andres
172 bronze badges
-
1what is your problem here with the codeRajaprabhu Aravindasamy– Rajaprabhu Aravindasamy2016年03月30日 15:26:51 +00:00Commented Mar 30, 2016 at 15:26
-
1var functionArray=[single, double, triple, quadruple];Md Johirul Islam– Md Johirul Islam2016年03月30日 15:30:24 +00:00Commented Mar 30, 2016 at 15:30
1 Answer 1
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.
answered Mar 30, 2016 at 15:27
Tim
5,7319 gold badges41 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Struggle with Andres
Very much appreciated!
Tim
@StrugglewithAndres You can accept this answer if it fits your needs! :)
lang-js