您的 operation 参数只是一个字符串,而不是真正的运算符。这就是为什么它不能如你所愿。所以,你有一些选择。
使用评估
您可以使用eval 函数将字符串作为一段代码动态运行,这样:
function calculate(x, y, operation) {
return eval(x + operation + y)
}
虽然它看起来如此简洁明了,但请记住,对于安全性、可维护性和来说,这通常是一种不好的做法性能原因 (more about it here)。
使用条件
有时最简单的想法是最好的选择:只需使用一些条件。
function calculate(x, y, operation) {
if (operation === '+') return x + y
else if (operation === '-') return x - y
else if (operation === '*') return x * y
else if (operation === '/') return x / y
else if (operation === '%') return x % y
else if (operation === '**') return x ** y
else return NaN
}
这似乎有点重复,但请记住,您不需要处理很多算术运算。其实all the binary arithmetic operators上面都有处理。
另一种语法是switch case 语句,但它只是一个更冗长的条件结构,想法保持不变。
使用带有函数的对象
受Nina Scholz' answer 强烈启发的另一种方法是在对象的帮助下将运算符的字符串表示映射到它们的等效函数:
function calculate(x, y, operation) {
var operators = {
'+': function (a, b) { return a + b },
'-': function (a, b) { return a - b },
'*': function (a, b) { return a * b },
'/': function (a, b) { return a / b },
'%': function (a, b) { return a % b },
'**': function (a, b) { return a ** b }
}
return operation in operators ? operators[operation](x, y) : NaN
}
如果在 ES2015+ 环境 (see the compatibility) 上,箭头函数 可以让它变得非常优雅:
function calculate(x, y, operation) {
const operators = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
'%': (a, b) => a % b,
'**': (a, b) => a ** b
}
return operation in operators ? operators[operation](x, y) : NaN
}
虽然我个人仍然认为简单的条件语句足以满足这种情况,但这种 Object 方法非常有趣,可以稍微展示一下 JavaScript 的灵活性。