传递数学运算符作为参数 [英] Passing a math operator as a parameter

查看:92
本文介绍了传递数学运算符作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Javascript中编写一个函数,允许我传入一个数学运算符和一个int列表,并为该列表中的每个项目应用运算符。

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.

从总和来看,这是我想出来的:

Thinking of it in terms of a sum, this is what I've come up with:

function accumulate(list, operator){
    var sum = 0;
    for each(var item in list){
        sum = accumulator(sum, item);
    }
    print(sum);
}

测试此代码会产生以下错误:

Testing this code produces the following error:

var list = new Array();
list[0] = 1;
list[1] = 2;
list[2] = 3;



js> accumulate(list, +);
js: "<stdin>", line 9: syntax error
js: accumulate(list, +);
js: ..................^
js: "<stdin>", line 9: Compilation produced 1 syntax errors.


推荐答案

您不能将运算符作为参数传递,但你可以传递一个函数:

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; });

这非常接近 Array.prototype.reduce 功能确实,虽然不完全是。要模仿 reduce 的行为,你必须从 list 中获取第一个元素并将其用作种子对于你的累加器,而不是总是使用0:

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);
}

这样,您可以计算列表的乘积(你的方法总是返回0):

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

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

更新:如果您正在开发支持ECMAScript 2015的新浏览器/ ES6(或使用像Babel这样的转换器),你也可以使用'箭头函数'语法使您的代码更紧凑:

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);

这篇关于传递数学运算符作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆