我如何通过第三次答复做出我的JavaScript答复?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何通过第三次答复做出我的JavaScript答复?相关的知识,希望对你有一定的参考价值。
我正在学习javascript,并创建了一个简单的脚本,该脚本询问您工作了多少小时。然后它将显示您是否工作足够,然后显示您之前输入的号码。
我把前两行作为
if (hours > 18)
alert('You have worked enough hours, thank you,');
else if (hours < 18)
alert('You have not worked enough hours.');
很好。但随后我添加了第三行:
else if (hours > 30)
alert('Wow, you have worked a lot of hours!');
这不起作用。
可能是什么问题?我将在此处保留完整脚本:
'use strict';
let hours = prompt('How many hours have you worked today?');
if (hours > 18)
alert('You have worked enough hours, thank you,');
else if (hours < 18)
alert('You have not worked enough hours.');
else if (hours > 30)
alert('Wow, you have worked a lot of hours!');
alert(`You have worked $hours hours`);
答案
您需要先检查条件“小时> 30”。希望下面的代码对您有帮助
<!DOCTYPE>
<html>
<script>
'use strict';
let hours = prompt('How many hours have you worked today?');
if (hours > 30)
alert('Wow, you have worked a lot of hours!');
else if (hours > 18)
alert('You have worked enough hours, thank you,');
else if (hours < 18)
alert('You have not worked enough hours.');
alert(`You have worked $hours hours`);
</script>
</html>
另一答案
您应先移动if (hours >= 30)
并先检查。否则,它将包含在条件if (hours >= 18)
中,并且永远不会执行。
<!DOCTYPE>
<html>
<script>
'use strict';
let hours = prompt('How many hours have you worked today?');
if (hours >= 30)
alert('Wow, you have worked a lot of hours!');
else if (hours >= 18)
alert('You have worked enough hours, thank you,');
else
alert('You have not worked enough hours.');
alert(`You have worked $hours hours`);
</script>
</html>
另一答案
首先,您必须检查小时数是否大于30,然后必须用18进行检查,因为首先如果您检查hours > 18
,那么当您输入大于18的小时数(包括小时数> 30时,它总是会变为true)也),因此您的支票else if (hours > 30)
永远不会执行。
<!DOCTYPE>
<html>
<script>
'use strict';
let hours = prompt('How many hours have you worked today?');
if (hours > 30)
alert('Wow, you have worked a lot of hours!');
else if (hours >= 18)
alert('You have worked enough hours, thank you,');
else if (hours < 18)
alert('You have not worked enough hours.');
alert(`You have worked $hours hours`);
</script>
</html>
以上是关于我如何通过第三次答复做出我的JavaScript答复?的主要内容,如果未能解决你的问题,请参考以下文章