如何检查 JS 中是否没有 eval returns
How to check if eval returns nothing in JS
如果我想检查一个 eval 函数是否 returns 什么都没有,我该怎么做?
我尝试做类似的事情:
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>
eval(code)
returns "the completion value of evaluating the given code. If the completion value is empty, undefined
is returned." MDN
在您的例子中,有效的数学表达式 returns a Number
。因此,您必须检查 typeof result == "Number"
。如果您想排除 NaN
、Infinity
等,请执行额外的检查,例如通过 isFinite(result)
.
如果您正在尝试构建一个计算器,您应该 be expecting 一个响应、一个异常或 null。
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
验证它是否是 Number,以及数学公式是否有效将帮助您确定可能的错误输出。
如果我想检查一个 eval 函数是否 returns 什么都没有,我该怎么做? 我尝试做类似的事情:
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>
eval(code)
returns "the completion value of evaluating the given code. If the completion value is empty, undefined
is returned." MDN
在您的例子中,有效的数学表达式 returns a Number
。因此,您必须检查 typeof result == "Number"
。如果您想排除 NaN
、Infinity
等,请执行额外的检查,例如通过 isFinite(result)
.
如果您正在尝试构建一个计算器,您应该 be expecting 一个响应、一个异常或 null。
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
验证它是否是 Number,以及数学公式是否有效将帮助您确定可能的错误输出。