首頁  >  問答  >  主體

使用變數的字串值作為要呼叫的函數的名稱

如何根據變數 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粉394812277P粉394812277236 天前392

全部回覆(1)我來回復

  • P粉801904089

    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]()

    回覆
    0
  • 取消回覆