猿问

在 for 循环中加载函数 - 变量 functionname[variable]

是否可以将函数命名为数组 [x]?


我正在寻找一种在 for 循环中加载不同函数的解决方案。我会像这个函数名一样声明函数。然后我将使用数组 = ["name", ...]; 在 foo 循环中调用函数;


function functionname["aaa"]() {

console.log("is for aaa");

}


array = ["aaa", "bbb", "ccc"];


for (var i = 0; i < array.length; i++) {

functionname[array[i]]();

}


慕标5832272
浏览 147回答 3
3回答

绝地无双

因此,如果我理解正确的话,您想遍历一个函数数组,调用数组中位于循环中当前迭代索引处的函数。我不知道你的目标是什么,但这是一种可能的解决方案,尽管有几种方法可以解决这个问题:const aaa = () => console.log('aaa');const bbb = () => console.log('bbb');const ccc = () => console.log('ccc');const array = [aaa, bbb, ccc];for (var i = 0; i < array.length; i++) {&nbsp; array[i]();}

慕森卡

您可以创建函数查找表。let functionname = {&nbsp; &nbsp; "aaa": () => {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for aaa")&nbsp; &nbsp; },&nbsp; &nbsp; "bbb": () => {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for bbb")&nbsp; &nbsp; }};没有箭头函数:var functionname = {&nbsp; &nbsp; "aaa": function aaa() {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for aaa");&nbsp; &nbsp; },&nbsp; &nbsp; "bbb": function bbb() {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for bbb");&nbsp; &nbsp; }};

潇潇雨雨

您可以将函数分配为对象的成员:let myObj = {&nbsp; &nbsp; "aaa": function () {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for aaa");&nbsp; &nbsp; },&nbsp; &nbsp; "bbb": function () {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for bbb");&nbsp; &nbsp; }};myObj["ccc"] = function () {&nbsp; &nbsp; &nbsp; &nbsp; console.log("is for ccc");&nbsp; &nbsp; };array = ["aaa", "bbb", "ccc"];for (var i = 0; i < array.length; i++) {&nbsp; &nbsp; myObj[array[i]]();}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答