Utilisez la valeur de chaîne de la variable comme nom de la fonction à appeler
P粉394812277
P粉394812277 2024-02-26 10:33:40
0
1
387

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粉394812277
P粉394812277

répondre à tous(1)
P粉801904089

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]()
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!