我正在尝试用 Javascript 制作一个计算器。 我有一个要求输入运算符的函数。 如果用户输入除 *、/、+ 或 - 以外的任何内容,我希望它再次请求操作员。 如果用户输入可接受的运算符之一,一切正常,但是,如果输入了错误的运算符,并且第二次执行该函数,则运算符的值在某种程度上是“未定义的”。而且我不知道为什么......当我在 if 语句中调用函数时,它是否不会跳回到 getOperator() 的开头,在那里我为操作符变量赋值? 谁能告诉我我做错了什么?
function getOperator() {
var operator = getStringInputWithPrompt('Please enter the operator:');
if ((operator !== "+") && (operator !== "*") && (operator !== "-") && (operator !== "/")) {
console.log("\nSorry that was not a valid operator");
getOperator();
} else {
return operator;
}
}
答案 0 :(得分:2)
您需要返回递归调用的结果。
function getOperator() {
var operator = prompt('Please enter the operator:');
if (operator !== "+" && operator !== "*" && operator !== "-" && operator !== "/") {
console.log("\nSorry that was not a valid operator");
return getOperator();
} else {
return operator;
}
}
console.log(getOperator());
因为写了一个计算器,你可以使用一个对象作为运算符并检查运算符是否存在并为这个运算符取函数。
const
operators = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b
};
function getOperator() {
let operator = prompt('Please enter the operator:');
if (operator in operators) return operator;
return getOperator(); // omit else after return
}
console.log(getOperator());
答案 1 :(得分:2)
在 if
中,您对 getOperator()
进行了递归调用,但您不对它的返回值执行任何操作。您可以立即退货。
console.log("\nSorry that was not a valid operator");
return getOperator();