Verwenden Sie den String-Wert der Variablen als Namen der aufzurufenden Funktion
P粉394812277
P粉394812277 2024-02-26 10:33:40
0
1
388

Wie rufe ich eine der aufgeführten Funktionen basierend auf dem Wert einer Variablen auf 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);

Das funktioniert nicht: window[被调用函数]();

Beim Ausführen window[called_function](); wird undefiniert angezeigt.

P粉394812277
P粉394812277

Antworte allen(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]()
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!