You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript if-else if-else语句异常:输入任意值均显示'none'求助

问题分析与解决方法

Hey there! Let's break down why your code is always showing 'none' no matter what score you input, and fix it step by step.

核心问题1:else语句的语法错误

Your final else (scores<60) grades='none'; is invalid syntax. Here's what's happening:

  • else doesn't take a condition—it only runs when all previous if/else if conditions fail.
  • In your code, JavaScript interprets (scores<60) as a standalone expression (it runs but does nothing useful), then executes grades='none'; as a separate line regardless of whether any earlier condition was true. That's why grades always gets overwritten to 'none' at the end.

核心问题2:字符串与数字的类型不匹配

The prompt() function returns a string, not a number. While JavaScript does implicit type conversion for comparisons, this can lead to unexpected behavior (e.g., if someone enters text instead of a score). It's better to explicitly convert the input to a number to ensure accurate comparisons.

修正后的代码

<script type="text/javascript">
  var grades, scores;
  // Convert prompt input to a number using Number()
  scores = Number(prompt('Write your score to convert it to grades'));

  // Fix the else logic and add proper condition checks
  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 {
    // All previous conditions failed, so score is ≤60
    grades = 'none';
  }

  document.write('Your grade name is ' + grades);
</script>

额外优化建议

  • Add validation for non-numeric inputs (e.g., if someone enters text instead of a score):
    if (isNaN(scores)) {
      document.write('Please enter a valid number!');
    } else {
      // Your grade logic here
    }
    
  • Use let/const instead of var for better scoping (modern JavaScript practice):
    let grades;
    const scores = Number(prompt('Write your score to convert it to grades'));
    

内容的提问来源于stack exchange,提问作者Caleb Hyun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:53:08