使用變數的字串值作為要呼叫的函數的名稱
P粉394812277
P粉394812277 2024-02-26 10:33:40
0
1
398

如何根據變數 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學習者快速成長!