Javascript 函数 - 将字符串参数转换为运算符 [英] Javascript function - converting string argument to operator
问题描述
如果我的问题不清楚,不知道如何表达,请见谅!
我正在尝试创建一个函数,该函数接受两个数字和一个包含运算符的字符串(例如+"、-"、*"、/").
I'm trying to create a function that takes two numbers and a string which contains an operator (e.g. '+', '-', '*', '/').
我在字符串上使用了 .valueOf() 来提取运算符,但是 num1 和 num2 参数似乎无法计算传递的数字参数.为什么会发生这种情况?
I've used .valueOf() on the string to extract the operator, however the num1 and num2 arguments do not seem to evaluate to the passed number parameters. Why is this happening?
function calculate(num1, operator, num2) {
return `num1 ${operator.valueOf()} num2`;
}
undefined
calculate(2, '+', 1);
"num1 + num2" //result
推荐答案
如果我理解你的要求,你可以使用 eval()
来实现:
If I understand your requirements, you could use eval()
to achieve this:
function calculate(num1, operator, num2) {
return eval(`${num1} ${operator} ${num2}`);
}
console.log(calculate(2, '+', 1)); // 3
或者,您可以通过使用 switch 块来避免使用 eval()
,它将使您的代码更易于调试并可能更安全:
Alternatively, you could avoid the use of eval()
by using a switch block, which would make your code easier to debug and potentially more secure:
function calculate(num1, operator, num2) {
switch (operator.trim()) { // Trim possible white spaces to improve reliability
case '+':
return num1 + num2
case '-':
return num1 - num2
case '/':
return num1 / num2
case '*':
return num1 * num2
}
}
console.log(calculate(2, '+', 1)); // 3
这篇关于Javascript 函数 - 将字符串参数转换为运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!