从数组调用函数
Calling a function from an array
我正试图通过从命令行读取的数字调用函数。这是我的代码:
saveuser = function(user, callback) {
//..
};
removeuser = function() {
//..
};
finduser = function() {
//..
};
updateuser = function() {
//..
}
var options = {
1: {
option: "Save a User",
execute: "saveuser( newuser, finduser )"
},
2: {
option: "Remove a User",
execute: "removeuser()"
},
3: {
option: "Find a User",
execute: "finduser"
},
4: {
option: "Update a User",
execute: "updateuser()"
}
}
function read() {
console.log("");
console.log( " Enter your choice: ");
stdin = process.stdin;
stdin.setEncoding('utf8');
stdin.on('data', choice);
};
function choice (data) {
data = parseInt(data);
console.log("You entered: " + data);
console.log("You choose to do: " + options[data]["option"]);
options[data]["execute"];
};
read();
现在什么也没发生。如果我把函数名不作为字符串放在数组中,它们会立即执行。我知道我可以用一个长if/elsif来处理这个问题,但是有一种方法可以用数组来做到这一点吗?
当您从函数名中删除引号时,它们立即执行的原因是您有包含()
的括号。所以去掉引号和圆括号:
saveuser
函数稍微复杂一些,因为需要传递参数。这可以通过使用.bind()
来处理,或者通过创建一个匿名函数(假设您在某处声明了newuser
)。
var options = {
1: {
option: "Save a User",
execute: saveuser.bind(null, newuser, finduser)
},
2: {
option: "Remove a User",
execute: removeuser
},
3: {
option: "Find a User",
execute: finduser
},
4: {
option: "Update a User",
execute: updateuser
}
}
你的最后一个问题是在choice()
函数中,你没有包括括号来实际执行函数。
options[data]["execute"]();
// ^^------ required to execute it
请查看更改
var saveuser = function() {
console.log('saveuser');
};
var removeuser = function() {
console.log('removeuser');
};
var finduser = function() {
console.log('finduser');
};
var updateuser = function() {
console.log('updateuser');
}
var options = {
1: {
option: "Save a User",
execute: function() {
saveuser(newuser, finduser );
}
},
2: {
option: "Remove a User",
execute: function () {
removeuser();
}
},
3: {
option: "Find a User",
execute: function() {
finduser();
}
},
4: {
option: "Update a User",
execute: function() {
updateuser();
}
}
}
function read() {
console.log("");
console.log( " Enter your choice: ");
stdin = process.stdin;
stdin.setEncoding('utf8');
stdin.on('data', choice);
};
function choice (data) {
data = parseInt(data);
console.log("You entered: " + data);
console.log("You choose to do: " + options[data]["option"]);
options[data].execute();
};
read();
您可以使用:
eval(options[data]["execute"]);
相关文章:
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用