我正在编写一个 JS 程序,我有一个条件可以根据输入进行一些算术运算。如果我遇到操作类型为“add”,我需要将两个值相加;如果我得到“times”作为我的运算符值,我需要相乘。
我尝试使用基本的 if 条件来解决我的问题,但也给出了很多样板代码。我正在尝试最小化代码并对其进行更多优化。
这是我尝试过的
if (otMethod === 'add') {
if (method === 'add'){
// some computation
result = ( (num + value) + otValue);
// some more computation
}
else{
// some computation
result = ( (num * value) + otValue);
// some more computation
}
} khác {
if (method === 'add'){
// some computation
result = ( (num + value) * otValue);
// some more computation
}
else{
// some computation
result = ( (num * value) * otValue);
// some more computation
}
}
在此,我必须更改基于 otMethod
的 OT 计算,并且必须基于方法 giá trị
对 num 进行算术运算。
我的问题是,我们能否根据 method
Và otMethod
的条件动态传递运算符本身,这样我就可以减少 if 条件的数量。提前致谢!
您不能传递运算符本身,但您不需要使用运算符。您可以只使用函数:
function add (a,b) { return a+b }
function times (a,b) { return a*b }
var op = {
add: add,
times: times
}
result = op[otMethod](op[method](num, value),otValue);
您可以通过按如下方式对其进行格式化使其更具可读性:
result = op[otMethod](
op[method](
num,
giá trị
),
otValue
);
这归结为您正在执行函数并将结果传递给另一个函数。例如,如果 otMethod
Và method
都是 add
,它就变成:
result = add( add(num,value), otValue )
将函数放在对象中允许我们使用方括号表示法来选择要执行的函数。上面这个操作的格式其实有个正式的名字:叫做Polish notation .
如果你可以使用 ES6,那么箭头函数语法会使代码非常简洁:
var op = {
add: (a,b) => a+b,
times: (a,b) => a*b
}
Epilogue - Polish Notation
Basically the regular notation formula
(a + b) * c
becomes
* + a b c
in Polish notation.
The advantage of Polish notation is that it does not require braces to denote operator precedence and also the operator and values are naturally in function call format:
*( +(a,b), c)
.
The programming language Lisp actually function like this. In Lisp +
Và *
are not operators but functions.
Tôi là một lập trình viên xuất sắc, rất giỏi!