首页 > 解决方案 > 使用 if/else 对数组中的数据进行排序,以便在不满足参数时生成一组数字或字符串

问题描述

我是一个菜鸟,到目前为止,我的学习有限,我很难理解如何做到这一点。任务是将输入的gpa从高到低排序,取平均值,拉高和低,将3.4以上的gpa全部分离输出。我可以做到这一点。我的问题是,如果没有高于 3.4 的 gpa 并且我正在用头撞墙几个小时,我正在尝试输出一个字符串,说明“今年没有好学生”。任何人都可以帮忙吗?这是代码和我的笔记:

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
<div id="output">
  </div>

  <script>
  var gpasOut = [];
  var gpas = [];

  while (gpasOut != "XXX")
  {
     gpasOut = prompt("Enter a GPA or XXX to Stop");

     if (gpasOut != "XXX")
     {
        gpas.push(parseFloat(gpasOut));
     }
  }

// This sets the vars as empty and prompts the user for integers and allows a break with "XXX";
// gpas.push pushes the values from the prompt (gpasOut) into gpas &
// parseFloat turns the strings into floating decimals;

  length = gpas.length;

// This gets the number of integers entered at prompt.

  function totalArray(total, num)
  {
     return total + num;
  }

  var total = gpas.reduce(totalArray);

  // This gets the sum of all numbers in array. Not sure I understand this code, but I was able to make it work.
  // I think it brings the numbers from the right (num) into the number on the left (total), thus "reducing" it.
  //
  // I'm sure there is a better way.

  var average = total / length;
// This gives the average GPA

  var sorted = gpas.sort(function (a, b)
  {
     return b - a
  });

  // This sorts the GPAs highest to lowest. Not sure I understand how it works.
  var badGpas = "<p>There were no good students this year. Try again next year!</p>";
  let goodGpas = [];
  for (let i = 0; i < gpas.length; i++)
  {
     if (gpas[i] >= 3.4)
     {
        goodGpas.push(gpas[i]);
      }

  else {
  badGpas
  }
}

// Here I want to print the string in BadGpas if there were NO gpas above 3.4!


  document.getElementById('output').innerHTML =
    "<h2>GPAs</h2><h3>Sorted Highest to Lowest: </h3>" + sorted.join("<br>")
      +"<h3>Class Average GPA is</h3>" + average + "<br>"
        + "<h3>The Highest is:</h3>" + gpas[0]
          + "<h3>The Lowest is:</h3>" + gpas[gpas.length-1]
            + "<h3>Outstanding GPAs (above 3.4)</h3>" + goodGpas.join("<br>")+badGpas;

  </script>

  </body>
</html>

标签: javascriptarrayssortingif-statement

解决方案


基于你所拥有的,你可以将 badGpas 变量初始化为一个空字符串:

let badGpas = '';

然后,在您检查了循环中的 gpas 并将所有高于 3.4 的 gpas 推入 goodGpas 数组后,您可以检查该数组是否为空。如果数组为空,则将 badGpas 值设置为要显示的文本:

let badGpas = '';
let goodGpas = [];

for (let i = 0; i < gpas.length; i++)
{
   if (gpas[i] >= 3.4)
   {
      goodGpas.push(gpas[i]);
    }  
}
if (goodGpas.length === 0) {
    badGpas = "<p>There were no good students this year. Try again next year!</p>";
}

推荐阅读