【问题标题】:Is there a way to store an arithmetic operator in a variable and use the variable itself within a calculation in JavaScript? [duplicate]有没有办法将算术运算符存储在变量中并在 JavaScript 的计算中使用变量本身? [复制]
【发布时间】:2021-08-11 12:02:45
【问题描述】:

使用以下 3 个变量 - 我想用设置的运算符变量来计算两个数字。例如 -> num1 * num2..

const num1 = 10;
const num2 = 4;
const operator = `*`; //Could be any arithmetic operator

我知道这可以使用 if 或 switch 语句来完成,但我很想知道是否有办法在实际计算中使用操作变量本身以更少的代码行来完成。

我尝试了以下事情(我主要期望他们会变成他们所做的那样):

console.log(num1 + operation + num2);    //Outputs: "10*4"

console.log(num1, operation, num2);    //Outputs: 10 "*" 4

console.log(`${num1} ${operation} ${num2}`);    //Outputs: "10 * 4"

console.log(num1 operation num2);    //Outputs: Error

const calculation = num1 operation num2; console.log(calculation);    //Outputs: Error

console.log(1 + operation + 2);    //Outputs: "1*2"

console.log(Number(1 + operation + 2));    //Outputs: NaN

那么有什么我还没有尝试过的东西可以使这项工作发挥作用,还是不能像这样完成?

【问题讨论】:

  • 在 JavaScript 中没有直接的方法可以做到这一点。在类似 Lisp 的语言中,“操作符”是函数,因此您可以实现您所尝试的。您当然可以将自己的一组函数作为对象的属性。

标签: javascript variables operators arithmetic-expressions


【解决方案1】:

您可以获取一个带有所需运算符的对象,测试该运算符是否存在,然后使用它。

var operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    },
    calculate = function (val1, val2, sign) {
        if (sign in operators) {
            return operators[sign](val1, val2);
        }
    }

console.log(calculate(6, 7, '*'));

【讨论】:

    猜你喜欢
    • 2012-05-12
    • 1970-01-01
    • 2012-12-24
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 2020-01-26
    相关资源
    最近更新 更多