如何通过JavaScript中字符串形式的名称访问函数?



假设我在一个函数内部,并且我在它内部创建了许多函数。从它们中,我想通过字符串形式的名称访问函数。我该怎么做呢?

function main(){
function a(){return "a function called"}
function b(){return "b function called"}
function c(){return "c function called"}
function d(){return "d function called"} // Please assume that these functions do very different stuffs, so that we cannot use ternary ifs (It is just a rough example)
const randomFunction = prompt("Which function do you want to call?") // Please consider that we use this user input to ask user type something from a, b, c or d. Obviously return value of prompt function would be a string
// Now I want to access the function by the same name, user entered and I also want to call it.
// So what can be the best approach to solve this problem, except from using "eval" or "Function"
}
main()

将其转换为对象并按键访问。例如

假设我在一个函数中,并且在其中创建了许多函数。从它们中,我想通过字符串形式的名称访问函数。我该怎么做呢?

const randomFunc =  {
a: function a(){return "a function called"},
b: function b(){return "b function called"},
c: function c(){return "c function called"},
d: function d(){return "d function called"},
}
console.log(randomFunc.a)

然后,您可以通过用户输入访问函数。

function main(){ function a(){return "a function called"} function b(){return "b function called"} function c(){return "c function called"} function d(){return "d function called"} // Please assume that these functions do very different stuffs, so that we cannot use ternary ifs (It is just a rough example) const randomFunction = prompt("Which function do you want to call?") // Please consider that we use this user input to ask user type something from a, b, c or d. Obviously return value of prompt function would be a string // Now I want to access the function by the same name, user entered and I also want to call it. // So what can be the best approach to solve this problem, except from using "eval" or "Function" return d; } main()