Javascript 函数 - 将字符串参数转换为运算符
Javascript function - converting string argument to operator
抱歉,如果我的问题不清楚,我不确定如何表达!
我正在尝试创建一个函数,它接受两个数字和一个包含运算符(例如“+”、“-”、“*”、“/”)的字符串。
我在字符串上使用了 .valueOf() 来提取运算符,但是 num1 和 num2 参数似乎没有评估传递的数字参数。为什么会这样?
function calculate(num1, operator, num2) {
return `num1 ${operator.valueOf()} num2`;
}
undefined
calculate(2, '+', 1);
"num1 + num2" //result
如果我理解您的要求,您可以使用 eval()
来实现:
function calculate(num1, operator, num2) {
return eval(`${num1} ${operator} ${num2}`);
}
console.log(calculate(2, '+', 1)); // 3
或者,您可以通过使用开关块来避免使用 eval()
,其中 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
做你想做的事情的最好方法是使用一个将运算符名称映射到函数的对象。
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));
抱歉,如果我的问题不清楚,我不确定如何表达!
我正在尝试创建一个函数,它接受两个数字和一个包含运算符(例如“+”、“-”、“*”、“/”)的字符串。
我在字符串上使用了 .valueOf() 来提取运算符,但是 num1 和 num2 参数似乎没有评估传递的数字参数。为什么会这样?
function calculate(num1, operator, num2) {
return `num1 ${operator.valueOf()} num2`;
}
undefined
calculate(2, '+', 1);
"num1 + num2" //result
如果我理解您的要求,您可以使用 eval()
来实现:
function calculate(num1, operator, num2) {
return eval(`${num1} ${operator} ${num2}`);
}
console.log(calculate(2, '+', 1)); // 3
或者,您可以通过使用开关块来避免使用 eval()
,其中 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
做你想做的事情的最好方法是使用一个将运算符名称映射到函数的对象。
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));