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.
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.You can also reference the function directly instead of using a string, like this: