这里的问题是,随着输出的到来,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"
实际输出为
"Zero Value"
undefined
有人建议为什么我的代码与输出一起输出未定义的内容?预先感谢。
答案 0 :(得分:1)
这是因为如果在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));
答案 1 :(得分:0)
function isPositive(a){
try{
if(a>0) return "YES";
if(a<0) throw "Negative Value";
if(a == 0) throw "Zero Value";
}catch(err)
{
return err;
}
}
console.log(isPositive(0));
我找到了答案,此代码对我有用,并给出了适当的结果。