使用变量的字符串值作为要调用的函数的名称
P粉394812277
P粉394812277 2024-02-26 10:33:40
[JavaScript讨论组]

如何根据变量 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]()
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号