How do I call one of the listed functions based on the value of the variable Called_function
?
function a() { alert('You called the a function.'); } function b() { alert('You called the b function'); } function c() { alert('You called the c function'); } const possible_strings = ["a", "b", "c"]; const called_function = Math.floor(Math.random() * possible_strings.length);
This doesn't work:
window[called function]();
When running window[called_function]();
, it shows undefined.
P粉8019040892024-02-27 00:42:50
You set the Called_function
to the index of the item in the array. Then you need to look up that index in the array to get the function name.
function a() { alert('You called the a function.'); } function b() { alert('You called the b function'); } function c() { alert('You called the c function'); } const possible_strings = ["a", "b", "c"]; const called_function = possible_strings[Math.floor(Math.random() * possible_strings.length)]; window[called_function]()
You can also reference the function directly instead of using a string, like this:
function a() { alert('You called the a function.'); } function b() { alert('You called the b function'); } function c() { alert('You called the c function'); } [a,b,c][Math.random()*3|0]()