Passing a math operator as a parameter

前端 未结 6 1140
长发绾君心
长发绾君心 2021-01-03 18:45

I\'d like to write a function in Javascript that allows me to pass in a mathematical operator and a list of ints and for each item in that list, apply the operator to it.

6条回答
  •  别那么骄傲
    2021-01-03 18:54

    You can't pass an operator as a parameter, but you can pass a function:

    function accumulate(list, accumulator){   // renamed parameter
        var sum = 0;
        for(var i = 0; i < list.length; i++){ // removed deprecated for…each loop
            sum = accumulator(sum, list[i]);
        }
        print(sum);
    }
    
    accumulate(list, function(a, b) { return a + b; });
    

    This is pretty close to what the Array.prototype.reduce function does, though not exactly. To mimic the behavior of reduce, you'd have to get the first element from list and use that as the seed for your accumulator, rather than always using 0:

    function accumulate(list, accumulator, seed){
        var i = 0, len = list.length;
        var acc = arguments.length > 2 ? seed : list[i++];
        for(; i < len; i++){
            acc = accumulator(acc, list[i]);
        }
        print(acc);
    }
    

    This way, you could compute the product of list (your method would always return 0):

    accumulate(list, function(a, b) { return a * b; });
    

    Update: If you're developing for newer browsers that support ECMAScript 2015 / ES6 (or using a transpiler like Babel), you can also use 'arrow function' syntax to make your code a bit more compact:

    accumulate(list, (a, b) => a * b);
    

提交回复
热议问题