new Function() with variable parameters

前端 未结 10 682
傲寒
傲寒 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.

提交回复
热议问题