说我下面有数组
var someStuff = [
"start", { one: "one"},
"setSomething", "foobar",
"someBool", true
];
如何将其转换为以下内容
var someStuff = [
MainFunc.start({one: "one"}),
MainFunc.setClientId('foobar'),
MainFunc.someBool(true)
];
答案 0 :(得分:0)
这样尝试(您需要使用箭头函数,否则该函数将被直接调用):
var someStuff = [
"start", { one: "one"},
"setSomething", "foobar",
"someBool", true
];
let output = []
for(let i=0, j=0; i<someStuff.length; i+=2, j++) {
let functionName = someStuff[i];
let functionArgs = someStuff[i+1];
output[j] = () => MainFunc[functionName](functionArgs);
}
console.log(output);
答案 1 :(得分:0)
我认为您可能想这样做
function mainFunc() {
this.start = function(obj) { console.log("start",obj) };
this.setSomething = function(obj) { console.log("set",obj) };
this.someBool = function(obj) { console.log("bool",obj) };
}
var someStuff = {
"start": { "one":"one"},
"setSomething": "foobar",
"someBool": true
};
var mf = new mainFunc();
for (var a in someStuff) {
mf[a](someStuff[a])
}
答案 2 :(得分:0)
为获得更好的可读性,请定义带有操作及其参数的对象数组。
const mainFunc = {
start: (param) => console.log('start', param),
setSomething: (param) => console.log('SetSomething', param),
someBool: (param) => console.log('someBool', param)
}
var someStuff = [
{ action: "start", param: { one: "one"} },
{ action: "setSomething", param: "foobar" },
{ action: "someBool", param: true }
];
someStuff.forEach(stuff => {
if (typeof mainFunc[stuff.action] === 'function') {
mainFunc[stuff.action](stuff.param);
}
});
答案 3 :(得分:0)
假设您想要一个包含多个函数调用结果的数组,这就是获取方法。您需要遍历数组,从MainFunc对象获取每个函数,然后每次都调用它。
我包括了一个不存在的函数的处理,这恰好在您的示例中(也许不是故意的)。
var MainFunc = {
start : function(x) { return "start called with " + x.toString(); },
setClientId : function(x) { return "setClientId called with " + x.toString(); },
someBool : function(x) { return "someBool called with " + x.toString(); }
}
var someStuff = [
"start", { one: "one" },
"setSomething", "foobar",
"setClientId", "foobar",
"someBool", true
];
var result = Process(someStuff);
function Process(arr) {
var result = [];
for (var i = 0; i < arr.length; i += 2) {
let fnToCall = MainFunc[arr[i]];
let fnResult = fnToCall ? fnToCall(arr[i + 1]) : "(unknown: '" + arr[i] + "')";
result.push(fnResult);
}
return result;
}
console.log(result);