How to call one function among many other functions randomly in Javascript ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 82

How to call one function among many other functions randomly in Javascript ?

6th Jul 2017, 1:38 AM
HOHOUETO Ronald Boris
HOHOUETO Ronald Boris - avatar
6 Answers
+ 19
function f_one() {} function f_two() {} function f_three() {} var f_arr = [f_one,f_two_,f_three]; var i = Math.floor(Math.random()*f_arr.length); f_arr[i]();
6th Jul 2017, 1:46 AM
visph
visph - avatar
+ 58
Thanks ;)
6th Jul 2017, 1:51 AM
HOHOUETO Ronald Boris
HOHOUETO Ronald Boris - avatar
+ 4
@Mohammad Bahoodh, I am sorry to inform you that your strategy does not work if the function was actually declared inside another function, which is how I do most of my code (hiding functions & variables which do not need to accessible outside my code, or if it needs to be, I make a single variable which has only certain functions exposed on an object it gets assigned to).
15th Jul 2017, 4:33 AM
Katie (Ctrl-Alt-Cuteness)
Katie (Ctrl-Alt-Cuteness) - avatar
6th Jul 2017, 8:47 PM
Ata
Ata - avatar
+ 3
To sum up the answer @visph made, when declared like that, they are variables for the current scope (for web pages, if not in an enclosing function, it probably will also be placed on the window object).
10th Jul 2017, 2:24 PM
Katie (Ctrl-Alt-Cuteness)
Katie (Ctrl-Alt-Cuteness) - avatar
0
you can access all functions from window object. just put all function names in an array then use aomething like this: let arr = ["func_one", "two"] window[arr[Math.floor(Math.random()*arr.length)]]
13th Jul 2017, 8:27 AM
Mohammad Bahoosh
Mohammad Bahoosh - avatar