+ 82
How to call one function among many other functions randomly in Javascript ?
6 Respuestas
+ 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]();
+ 58
Thanks ;)
+ 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).
+ 3
This code explains further
https://code.sololearn.com/WCnNImldl210/?ref=app
+ 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).
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)]]