new Function() with variable parameters

前端 未结 10 658
傲寒
傲寒 2020-12-25 11:38

I need to create a function with variable number of parameters using new Function() constructor. Something like this:

args = [\'a\', \'b\'];
bod         


        
10条回答
  •  情歌与酒
    2020-12-25 12:03

    In this sample i used lodash:

    function _evalExp(exp, scope) {
      const k = [null].concat(_.keys(scope));
      k.push('return '+exp);
      const args = _.map(_.keys(scope), function(a) {return scope[a];});
      const func = new (Function.prototype.bind.apply(Function, k));
      return func.apply(func, args);
    }
    
    _evalExp('a+b+c', {a:10, b:20, c:30});
    

提交回复
热议问题