如何根據變數 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粉8019040892024-02-27 00:42:50
您將 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]()