[英]How to execute node js functions one after another which dynamically listed using their names in a string array
我需要在Node.js程序中实现以下目标。
向我建议一种更好的方法来实现此目标或已经实现此目标的代码段。
var functions = ["foo", "bar", "baz"];
我们遍历函数列表并调用__call
函数。
functions.forEach(function(f){
__call(f);
});
此步骤取决于框架。 如果使用节点,则必须使用global
对象。 如果使用浏览器(HTML),则必须使用window
对象。
对于前者,请使用:
__call = function(f) {
var args = [];
for(var i = 1; i<arguments.length; i++){
args.push(arguments[i])
};
console.log(args);
global[f].apply(null, args);
};
对于后者,请使用:
__call = function(f) {
var args = [];
for(var i = 1; i<arguments.length; i++){
args.push(arguments[i])
};
console.log(args);
window[f].apply(null, args);
};
唯一的区别是我们使用window
或global
字典来访问该函数。
编辑:添加了传递参数。
你可以这样
function foo(v){console.log("foo: ",v)}; function bar(v){console.log("bar: ",v)}; var funs = ["foo", "bar"], i = 0; while (i < funs.length) this[funs[i]](i++);
当然,您的函数定义可能驻留在特定范围内,并且您可能需要从what ..!内部调用它们。 在那种情况下,您当然可以将上面的代码包装在一个函数中,并将其绑定到您定义函数的范围内。
var obj = { foo: function(v){console.log("foo: ",v)}, bar: function(v){console.log("bar: ",v)} }, funs = ["foo", "bar"], runner = function(a){ var i = 0; while (i < a.length) this[a[i]](i++); }.bind(obj); runner(funs);
您可以通过函数名称来调用它,如下所示:
const functions = ['index','push'...];
functions[0]() // write your parameters inside. this will call 'index'
如果这些函数不是异步的,则只需一个接一个地编写调用。 如果它们是异步的,请使用async.waterfall或async.series之类的帮助器。
见1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.