Heim  >  Fragen und Antworten  >  Hauptteil

Verwenden Sie den String-Wert der Variablen als Namen der aufzurufenden Funktion

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粉394812277P粉394812277236 Tage vor399

Antworte allen(1)Ich werde antworten

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

    Antwort
    0
  • StornierenAntwort