gpt4 book ai didi

javascript - 将变量操作数应用于运算符

转载 作者:行者123 更新时间:2023-12-02 22:46:21 26 4
gpt4 key购买 nike

我有一个表格:

data:[
{ operator: '*', operand1: 45, operand2: 80 },
{ operator: '*', operand1: 14, operand2: 47 },
{ operator: '+', operand1: 80, operand2: 6 }
];

我需要解析 JSON 数据并返回一组答案。我对如何将变量运算符“应用”到操作数感到困惑。谢谢!

最佳答案

将运算符映射到调用时执行运算符的函数,例如:

const operatorFns = {
'*': (a, b) => a * b,
'+': (a, b) => a + b
// etc
};

const data = [
{ operator: '*', operand1: 45, operand2: 80 },
{ operator: '*', operand1: 14, operand2: 47 },
{ operator: '+', operand1: 80, operand2: 6 }
];

const results = data.map(item => operatorFns[item.operator](item.operand1, item.operand2));
console.log(results);

关于javascript - 将变量操作数应用于运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58385840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com