如果我想检查eval函数是否返回任何内容,我该怎么做? 我试着做类似的事情:
if (eval("iwuoinuvwoienvuwope") == "") {
// Do something
alert("Oh NO!");
}
但是,当我确实喜欢没有任何事情发生时。
这是我的完整代码:
function calc() {
var cal = prompt("Your math....", "1 + 1");
if (cal == null) {
alert("If you don't have a math problem you can gtfo!");
} else if (cal == false) {
alert("If you don't have a math problem you can gtfo!");
}
/* Here I Check if eval is empty */
/* Here it doesn't work */
else if (eval(cal) == "") {
alert("Could you be more specific");
}
/* */
else {
alert("The answer is " + eval(cal));
}
}
<button onclick="calc();">Calculator</button>
答案 0 :(得分:2)
eval(code)
返回&#34;评估给定代码的完成值。如果完成值为空,则返回undefined
。&#34; MDN
在您的情况下,有效的数学表达式返回Number
。因此,您必须检查typeof result == "Number"
。如果您要排除NaN
,Infinity
等,请执行其他检查,例如isFinite(result)
。
答案 1 :(得分:0)
如果您正在尝试构建计算器,则应be expecting响应,异常或为空。
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
验证它是否为Number,如果数学公式有效,将帮助您识别可能的错误输出。