使用变量的字符串值作为要调用的函数的名称
P粉394812277
P粉394812277 2024-02-26 10:33:40
0
1
393

如何根据变量 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);

这不起作用: window[被调用函数]();

运行 window[called_function](); 时,显示未定义。

P粉394812277
P粉394812277

全部回复(1)
P粉801904089

您将 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 = possible_strings[Math.floor(Math.random() * possible_strings.length)];

window[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'); }

[a,b,c][Math.random()*3|0]()
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!