如何根据变量 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](); 时,显示未定义。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您将
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]()