简体   繁体   中英

If and else if and else - javascript

I just started to study Javascript and I am struggling to solve if and else if usage. 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. 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. Either use else-if:

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

or just 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(...));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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