如何在javascript中访问算术运算符作为函数? [关闭]

问题描述 投票:-2回答:4

javascript中编写如下内容的惯用方法是什么?

# in python
import operator
def foo(f, a, b): return f(a,b)

foo(operator.add, 2, 3) # returns 5
foo(operator.mul, 2, 3) # returns 6

- 编辑

我对名称“add”,“mult”等没有特别的倾向。例如,在R中,有一个简单的香草反引号运算符来获取原语。在那之前,sh

对我来说,这是一个更具表现力的编写代码方法的问题,具有运行时效率或至少避免不必要的运行时间负担。为什么我不想避免函数调用的成本?

这并不意味着我没有接受你的建议。我真的有,亲爱的陌生人:)但我也希望我的代码运行得更快,如果有一个解决方法,尤其是。当谈到内循环。

javascript
4个回答
2
投票

在javascript中没有等效的operator,你不能像在Python中那样在javascript中重载运算符。尽管如此,函数是一流的对象,因此您可以创建一个类似于您发布的函数的函数。你只需要创建自己的add mul等:

let operator = {
    add(a, b) {return a + b},
    mul(a, b) {return a * b}
}

const foo = (f, a, b) => f(a,b)

console.log(foo(operator.add, 2, 3)) // returns 5
console.log(foo(operator.mul, 2, 3)) // returns 6

0
投票
var operator = {
  add: function(a, b) { return a + b; },
  mul: function(a, b) { return a * b; }
};

var foo = function(f, a, b) { return f(a, b) };

然后你可以这样做:

console.log(foo(operator.add, 1, 2)); // 3

0
投票

在JavaScript中,您可以创建可重用的函数,为您返回算术计算。

例如。如果你想要一个添加功能,你可以创建一个像这样的可重用函数:

function add(a,b) {
    return a + b;
}

同样的方法适用于其他类型的算术计算:

function mult(a,b) {
    return a * b;
}
function subtr(a,b) {
    return a - b;
}
function divd(a,b) {
    return a / b;
}

然后可以使用参数调用此可重用函数,它将返回参数的计算结果。

add(25, 75); // will return 100
subtr(76, 64); // will return 12
mult(15, 20); // will return 300
divd(300, 60); // will return 5

对于任何其他类型的算术计算,您也可以使用与上述相同的方法。


-1
投票

您可以编写自己的add函数,它接受任意数量的运算符,并将函数传递给foo函数,就像在python中一样。

© www.soinside.com 2019 - 2024. All rights reserved.