Use the string value of the variable as the name of the function to be called
P粉394812277
P粉394812277 2024-02-26 10:33:40
0
1
418

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粉394812277
P粉394812277

reply all(1)
P粉801904089

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]()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template