为了账号安全,请及时绑定邮箱和手机立即绑定

为什么这段js代码中只有if,没有else?

为什么这段js代码中只有if,没有else?

Gnayoul 2016-08-13 19:12:52
window.onload = initAll;function initAll() {var ans = prompt("Enter a number","");try {if (!ans || isNaN(ans) || ans<0) {throw new Error("Not a valid number");}alert("The square root of " + ans + " is " + Math.sqrt(ans));}catch (errMsg) {alert(errMsg.message);}}
查看完整描述

3 回答

已采纳
?
snowmanJS

TA贡献89条经验 获得超53个赞

/*

  1. try{}这段语句是抛出异常;catch(errMsg){}是捕获异常。

  2. 如果,if语句中条件为真(即,变量ans为非数字或是小于0的数字时)时,就会执行throw new Error("Not a valid number");抛出一个异常。此时if后面的语句alert("The square root of " + ans + " is " + Math.sqrt(ans));就不会被执行。接着执行catch (errMsg) {alert(errMsg.message)}捕获到异常并弹出异常为:Not a valid number;

  3. 如果,if语句中条件为假(即,变量ans为大于或等于0的数字)时,就不会抛出异常,继而执行alert("The square root of " + ans + " is " + Math.sqrt(ans));,catch (errMsg) {alert(errMsg.message)}也不会被执行!

  4. 综上,else在这里就没有必要了。

*/

try {

if (!ans || isNaN(ans) || ans<0) {

throw new Error("Not a valid number");

}

alert("The square root of " + ans + " is " + Math.sqrt(ans));

}

catch (errMsg) {

alert(errMsg.message);

}

}



查看完整回答
2 反对 回复 2016-08-14
?
stone310

TA贡献361条经验 获得超191个赞

没有else就是单纯判断,true就执行语句1,然后无论true还是false都执行语句2

if(){执行语句1};

执行语句2;

如果有else就判断,true就执行语句1,false就执行语句2

if(){执行语句1};

else{执行语句2};

查看完整回答
1 反对 回复 2016-08-13
?
chwech

TA贡献63条经验 获得超18个赞

话说不用else子句也行的,有什么奇怪的?

查看完整回答
1 反对 回复 2016-08-13
  • Gnayoul
    Gnayoul
    就是说else可以省略?刚学js,不太懂
  • chwech
    chwech
    可以,你先把基础语法过一次就好了
  • 3 回答
  • 0 关注
  • 2320 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信