【问题标题】:Issue with evaluating average of an array评估数组平均值的问题
【发布时间】:2020-09-24 17:53:02
【问题描述】:

我正在尝试显示一系列测试分数,在它们之上显示这些分数的平均值。这是我正在使用的代码:

var clickDisplayResults = function () {
  $("results").value = "";
  function calculate(scores) {
    var i = 0, sum = 0, len = scores.length;
    while (i < len) {
      sum = sum + scores[i++];
    };
    return sum / len;
};

var average = calculate(scores);
$("results").value = "The average score is: " + parseInt(average) + "\n";
$("results").value += "High Score: " + Math.max.apply(null, scores) + "\n";
$("results").value += "Low Score: " + Math.min.apply(null, scores) + "\n" + "\n";
for (var i = 0; i < names.length; i++) {
  $("results").value += names[i] + ", " + scores[i] + "\n";
};

但是,当我这样做时,在添加新分数后,我得到了一个荒谬范围内的平均值。

这里是加分码:

var clickAddScore = function () {
  if ( $("name").value == "" || $("score").value < 0 || $("score").value > 100 || isNaN($("score").value) ) {
    alert("Please enter a valid name and score");
    $("name").value = "";
    $("score").value = "";
    return false;
  };
  else {
    names[names.length] = $("name").value;
    scores[scores.length] = $("score").value;
    $("name").value = "";
    $("score").value = "";
  };
};

任何建议将不胜感激。

【问题讨论】:

  • value是字符串,不是数字,需要转成数字
  • 仅供参考:一遍又一遍地执行$("name").value 对性能不利。将其存储到变量中。

标签: javascript jquery arrays average


【解决方案1】:

您正在处理字符串并将其视为数字

console.log("100" + 100);

您需要将字符串转换为数字。您可以使用 parseInt、parseFloat、Number 或 Unary plus。

您的代码效率有点低,因为您一直在访问 DOM 以获取值,因此请声明一些变量。而你的 else 语句是错误的。

var clickAddScore = function() {
  var studentName = $("name").value.trim();
  var score = Number($("score").value);
  if (studentName == "" || score < 0 || score > 100 || isNaN(score)) {
    alert("Please enter a valid name and score");
  } else {
    names.push(studentName);
    scores.push(score);
  }
  $("name").value = "";
  $("score").value = "";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-03
    • 2013-03-31
    • 2014-09-16
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    相关资源
    最近更新 更多