-1

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 does not work: window[called_function]();

When running window[called_function]();, it says undefined.

wgm
  • 1
  • 1
    Easiest thing to do is place your functions in an object. `const fns = { a: () => alert('...'),....}` And then `fns[called_function]()` – Keith May 18 '23 at 14:05
  • ```const called_function = possible_strings[Math.floor(Math.random() * possible_strings.length);];``` – Shri Hari L May 18 '23 at 14:06
  • You're doing the equivalent of `window[2]()`, not `window['c']()`…! – deceze May 18 '23 at 14:07

1 Answers1

0

You set called_function to the index of the item in the array. You need to then 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 functions directly, instead of using strings, 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]()
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • 1
    Option 2 is way better, mainly because it will keep working if the OP decided to place in a module. – Keith May 18 '23 at 14:13
  • This works and is a great solution but I still have a problem. a, b, and c are not of type string are they? My database returns these values as strings. How do I convert strings to the type listed above? The point of the random function was to abstract out the database operations for the purpose of this question. Also good catch on returning the index and not the actual value. Lol, would have caught that if I ran the code first or read it haha – wgm May 18 '23 at 14:27
  • Referring to option 1, why am I getting an error? caught TypeError: window[called_function] is not a function at window.onload (script.js:14:26) window.onload @ script.js:14 lo – wgm May 18 '23 at 14:29
  • @wgm ah ok, if the DB returns a string, then you need to use option 1. As I wrote at the beginning of the answer, you had set called_function to a number less than 3. Compare my code to yours, and you'll see that my version is slightly different because it then uses that index to get the string out of the array – Andrew Parks May 18 '23 at 14:56