如何从方法名称的数组构建方法链

问题描述 投票:2回答:2

让我告诉你什么,我想完成一个例子:

说我要调用一个函数子功能的子功能的子功能(等等,可以说,对于50个以上的子功能),如:

foo(arg).bar(other).foobar(int, str).execute(str)

和想象,有50多个子功能,所以这将是非常不切实际的键入出每个子调用。

SO:我怎样写一个函数来调用子功能等的子功能...(基于阵列的长度)?基于这样的一个数组(例如)在:

[["foo",["asdf"]],["bar",["other"]],["foobar",[123,"hi"]],["execute",["today"]]]

需要明确的是,我不是简单地试图调用数组与相应的参数单独的每个功能,我能做到这一点很容易有:

arr.forEach(x=>functionDictionary(x[0])(...x[1])

我想简单地得到这样的:

foo(arg).bar(other).foobar(int, str).execute(str)

由此:

[["foo",["asdf"]],["bar",["other"]],["foobar",[123,"hi"]],["execute",["today"]]]
javascript arrays function substring
2个回答
5
投票

使用reduce迭代阵列之上并调用每个函数,并沿着返回值到下一次迭代的累加器通过:

// using just a single object to make the indentation much more readable:
const obj = {
  foo(arg) {
    console.log('foo called with ' + arg);
    return this;
  },
  bar(arg2) {
    console.log('bar called with ' + arg2);
    return this;
  },
  foobar(argA, argB) {
    console.log('foobar called with ' + argA + ' ' + argB);
    return this;
  },
  execute(arg5) {
    console.log('execute called with ' + arg5);
    return this;
  }
};

const arr = [
  ["foo", ["asdf"]],
  ["bar", ["other"]],
  ["foobar", [123, "hi"]],
  ["execute", ["today"]]
];
arr.reduce((a, [key, args]) => a[key](...args), obj);

请注意,我在这里传递obj作为初始值,从而第一["foo"]可以访问obj.foo,而不是使用eval在命名foo电流范围引用变量。


1
投票

尝试

arr.forEach( x => r=r[x[0]](...x[1]) );

其中ARR包含有功能名称,参数您的阵列,R包含具有功能对象(以及在端部的结果)。

const o = {
  fun1(arg) { console.log('fun1 ' + arg); return this;},
  fun2(arg1,arg2) { console.log('fun2 ' + arg1 +'-'+ arg2); return this; },
  fun3(arg) { console.log('fun3 ' + arg); return this;},  
};

const arr = [
  ["fun1", ["abc"]],  
  ["fun2", [123, "def"]],
  ["fun3", ["ghi"]]
];


let r=o; // result
arr.forEach( x => r=r[x[0]](...x[1]) );

在情况下,如果你想打破调用链时,功能不会返回一个对象,然后用这个

arr.forEach( x => r= r ? r[x[0]](...x[1]) : 0 );

const o = {
  fun1(arg) { console.log('fun1 ' + arg); return this;},
  fun2(arg1,arg2) { console.log('fun2 ' + arg1 +'-'+ arg2); },
  fun3(arg) { console.log('fun3 ' + arg); return this;},  
};

const arr = [
  ["fun1", ["abc"]],  
  ["fun2", [123, "def"]],
  ["fun3", ["ghi"]]
];


let r=o; // result
arr.forEach( x => r= r ? r[x[0]](...x[1]) : 0 );
© www.soinside.com 2019 - 2024. All rights reserved.