sách gpt4 ăn đã đi

javascript - 如何根据 JS 中的条件传递算术运算符?对 'add' 说 +,对 'times' 说 *

In lại Tác giả: Walker 123 更新时间:2023-11-29 15:08:30 25 4
mua khóa gpt4 giày nike

我正在编写一个 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 进行算术运算。

我的问题是,我们能否根据 methodotMethod 的条件动态传递运算符本身,这样我就可以减少 if 条件的数量。提前致谢!

câu trả lời hay nhất

您不能传递运算符本身,但您不需要使用运算符。您可以只使用函数:

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

这归结为您正在执行函数并将结果传递给另一个函数。例如,如果 otMethodmethod 都是 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 +* are not operators but functions.

关于javascript - 如何根据 JS 中的条件传递算术运算符?对 'add' 说 +,对 'times' 说 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57302423/

25 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress