这里的问题是 JavaScript 的输出也显示未定义。我在 w3schools.com 和developers.mozilla 网站上看到了一些代码,并尝试了其他一些网站,但没有找到任何解决方案或关于我遇到的问题的任何解释。
我想在出现 0 或负值时抛出异常。
function isPositive(a) {
try {
if (a > 0) return "YES";
if (a < 0) throw "Negative Value";
if (a == 0) throw "Zero Value";
} catch (error) {
console.log(error);
}
}
console.log(isPositive(0));
预期输出为
“零值”
实际输出为
"Zero Value"
undefined
有什么建议为什么我的代码与输出一起打印未定义吗?提前致谢。
最佳答案
这是因为如果 try
中抛出任何错误,它不会停止代码的执行。如果您想在出错时停止该函数,只需删除 try-catch
并简单地 return
function isPositive(a){
if(a>0) return "YES"
if(a<0) return "Negative Value";
if(a == 0) return "Zero Value";
}
console.log(isPositive(0));
如果你想抛出错误,请将语句放在 try
之外
function isPositive(a){
if(a>0) return "YES"
if(a<0) throw ("Negative Value");
if(a == 0) throw ("Zero Value");
}
console.log(isPositive(0));
关于javascript - 为什么我的 JavaScript 代码打印未定义并抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55350980/