[英]Javascript function - converting string argument to operator
Apologies if my question is unclear, wasn't sure how to word it! 抱歉,如果我的问题不清楚,不知道如何说出来!
I'm trying to create a function that takes two numbers and a string which contains an operator (eg '+', '-', '*', '/'). 我正在尝试创建一个带两个数字的函数和一个包含运算符的字符串(例如'+',' - ','*','/')。
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. 我在字符串上使用.valueOf()来提取运算符,但是num1和num2参数似乎没有计算为传递的数字参数。 Why is this happening?
为什么会这样?
function calculate(num1, operator, num2) {
return `num1 ${operator.valueOf()} num2`;
}
undefined
calculate(2, '+', 1);
"num1 + num2" //result
If I understand your requirements, you could use eval()
to achieve this: 如果我了解您的要求,您可以使用
eval()
来实现此目的:
function calculate(num1, operator, num2) {
return eval(`${num1} ${operator} ${num2}`);
}
console.log(calculate(2, '+', 1)); // 3
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 : 或者,您可以通过使用开关块来避免使用
eval()
,这将使您的代码更容易调试并且可能更安全 :
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
The best way to do what you want is with an object that maps operator names to functions. 执行所需操作的最佳方法是使用将操作员名称映射到函数的对象。
const opmap = { "+": (x, y) => x + y, "-": (x, y) => x - y, "*": (x, y) => x * y, "/": (x, y) => x / y, }; function calculate(num1, operator, num2) { if (operator in opmap) { return opmap[operator](num1, num2); } } console.log(calculate(2, '+', 1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.