使用变量的字符串值作为函数名来调用[重复]

问题描述 投票:0回答:1

如何根据变量的值调用列出的函数之一

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[called_function]();

运行

window[called_function]();
时,它说undefined.

javascript function dynamic
1个回答
0
投票

您将

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

© www.soinside.com 2019 - 2024. All rights reserved.