new Function() with variable parameters

前端 未结 10 617
傲寒
傲寒 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:08

    If you're just wanting a sum(...) function:

    function sum(list) {
        var total = 0, nums;
        if (arguments.length === 1 && list instanceof Array) {
            nums = list;
        } else {
            nums = arguments;
        }
        for (var i=0; i < nums.length; i++) {
            total += nums[i];
        }
        return total;
    }
    

    Then,

    sum() === 0;
    sum(1) === 1;
    sum([1, 2]) === 3;
    sum(1, 2, 3) === 6;
    sum([-17, 93, 2, -841]) === -763;
    

    If you want more, could you please provide more detail? It's rather difficult to say how you can do something if you don't know what you're trying to do.

    0 讨论(0)
  • 2020-12-25 12:11

    You can do this:

    let args = '...args'
    let body = 'let [a, b] = args;return a + b'
    
    myFunc = new Function(args, body);
    console.log(myFunc(1, 2)) //3

    0 讨论(0)
  • 2020-12-25 12:11

    A new feature introduced in ES5 is the reduce method of arrays. You can use it to sum numbers, and it is possible to use the feature in older browsers with some compatibility code.

    0 讨论(0)
  • 2020-12-25 12:11
    function construct(){
             this.subFunction=function(a,b){
             ...  
             }
    }
    var globalVar=new construct();   
    

    vs.

    var globalVar=new function (){
                  this.subFunction=function(a,b){
                  ...
                  }
    }
    

    I prefer the second version if there are sub functions.

    0 讨论(0)
提交回复
热议问题