简体   繁体   English

如果和否则,如果和其他-javascript

[英]If and else if and else - javascript

I just started to study Javascript and I am struggling to solve if and else if usage. 我刚刚开始学习Javascript,我正在努力解决是否以及是否使用。 here is my code. 这是我的代码。 The problem is it kept showing 'none' results at the end no matter what numbers are put. 问题在于无论输入什么数字,结果始终显示“无”结果。 Can you explain it to me? 你能跟我解释一下吗?

<script type="text/javascript">
    var grades,scores;
    scores=prompt ('write your score to convert it to grades');
    if (scores>101)
    grades='high distinction';
    else if (scores>91)
    grades='distinction';
    else if (scores>81)
    grades='credit';
    else if (scores>71)
    grades='pass';
    else if (scores>61)
    grades='fail';
    else (scores<60)
    grades='none';
document.write ('your grade name is'+grades);

    </script>

The result of a prompt is always a string. prompt的结果始终是字符串。 Convert it to a number first to be safe: 为了安全起见,请先将其转换为数字:

scores = Number(prompt('write your score to convert it to grades'));

Also, your code here: 另外,您的代码在这里:

else(scores < 60)
grades = 'none';

else does not accept conditions like that. else不接受这样的条件。 Either use else-if: 可以使用else-if:

else if (scores < 60) grades = 'none';

or just else : else

else grades = 'none';

In full: 在全:

 var grades, scores; scores = Number(prompt('write your score to convert it to grades')); if (scores > 101) grades = 'high distinction'; else if (scores > 91) grades = 'distinction'; else if (scores > 81) grades = 'credit'; else if (scores > 71) grades = 'pass'; else if (scores > 61) grades = 'fail'; else grades = 'none'; document.write('your grade name is' + grades); 

您需要在使用提示时添加一个参数来尝试以下操作:scores = prompt('写您的分数以将其转换为成绩','');

您需要将响应转换为整数才能比较

You could simply Google this. 你可以简单地谷歌这个。 It is because your prompt returns a string and not an integer. 这是因为您的提示返回的是字符串而不是整数。 You need to parse it to a number. 您需要将其解析为一个数字。 Do

scores = parseInt(prompt(...));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM