我有一个要求用户选择运营商的功能。 选择运算符后,函数将运行以查看函数中是否有运算符。 如果有那么就好了,出来的结果就好了。但如果没有运算符(operator),您将无法输入数字,它应该立即返回消息“找不到运算符(operator)”。 但是相反,它循环遍历所有函数并仍然让用户输入数字,即使找不到运算符(operator)。这是代码
function go(oper, _num1, _num2) {
if (oper == "+") {
return _num1+_num2;
} else if(oper == "-") {
return _num1-_num2;
} else if(oper == "/"){
return _num1/_num2;
} else if(oper == "*"){
return _num1*_num2;
} else {
return "Sorry Operator not recognized";
}
}
alert( go( prompt("- , + , / , * Choose one = "), parseInt(prompt("Gimme a number")), parseInt(prompt("Second number")) ) );
如果找不到接线员,我希望代码停止询问号码。我应该怎么办? 提前致谢。 (抱歉,英语不是我的母语)
最佳答案
在这种情况下,您似乎并不真的需要函数参数,因为它们总是相同的...
其中一种方式:
let calc = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
}
alert( go() );
function go() {
let oper = prompt("- , + , / , * Choose the operator:");
if( oper in calc ){
let a = +prompt("Gimme a number:");
if( isNaN(a) ){ return "Not a number!"; }
let b = +prompt("Second number:");
if( isNaN(b) ){ return "Not a number!"; }
return calc[oper](a, b);
} else {
return "Sorry Operator not recognized";
}
}
关于javascript - 如果不满足功能如何停止javascript提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58670983/