search

Home  >  Q&A  >  body text

Use the string value of the variable as the name of the function to be called

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粉394812277P粉394812277305 days ago450

reply all(1)I'll reply

  • P粉801904089

    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]()

    reply
    0
  • Cancelreply