Maison  >  Questions et réponses  >  le corps du texte

Utilisez la valeur de chaîne de la variable comme nom de la fonction à appeler

Comment appeler l'une des fonctions répertoriées en fonction de la valeur d'une variable 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);

Cela ne fonctionne pas : window[被调用函数]();

Lors de l'exécution de window[called_function]();, il s'affiche comme indéfini.

P粉394812277P粉394812277236 Il y a quelques jours389

répondre à tous(1)je répondrai

  • P粉801904089

    P粉8019040892024-02-27 00:42:50

    Vous définissez Called_function sur l'index de l'élément dans le tableau. Ensuite, vous devez rechercher cet index dans le tableau pour obtenir le nom de la fonction.

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

    Vous pouvez également référencer la fonction directement au lieu d'utiliser une chaîne, comme ceci :

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

    répondre
    0
  • Annulerrépondre