如何使用输入框为数组添加值得到平均值?

时间:2016-07-17 17:18:03

标签: javascript arrays

在输入框中添加一个分数后,我无法获得分数的平均值。可以弄清楚我哪里出错了。我能够将输入添加到数组但无法计算平均值。

var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 99];
var average;
var total = 0;
var highestScore = 0;
var name = "";

var $ = function (id) { return document.getElementById(id); };

//validate entries and add to array
var addScore = function() {
  var nameInput = $("nameInput").value;
  var scoreInput = $("scoresInput").value;
  if ((nameInput == "" || scoreInput == "") || (scoreInput < 0 || scoreInput > 100 )){
    alert("You must enter a name and a valid score");
  }
  else {
    names[names.length] = nameInput;
    scores[scores.length] = scoreInput;
  }
};
//then calculate the average and highest score
var displayResults = function () {

  for (var i = 0; i < scores.length; i++) {
    total = total + scores[i];      
    if (scores[i] > highestScore) {
      highestScore = scores[i];
      name = names[i];

    }
  }
  average = parseInt(total/scores.length);
  $("results_header").innerHTML = ("Results");
  $("results_text").innerHTML = ("\nAverage score is " + average + "<br>" + "\nHigh score = " + name + " with a score of " + highestScore);

};
//display scores table
var displayScores = function() {
  $("scores_header").innerHTML = ("Scores");
  $("names").innerHTML = ("Names");
  $("scores").innerHTML = ("Scores");
  var table = $("scores_table");
  for(var i=0; i < names.length;i++) {
    var row = table.insertRow(table.rows.length);
    var cell = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell.innerHTML = names[i];
    cell2.innerHTML = scores[i];
  }
};

window.onload = function () {
  $("add").onclick = addScore;
  $("display_results").onclick = displayResults;
  $("display_scores").onclick = displayScores;
};
<main>
  <h1>Use a Test Score array</h1>

  <label for="name">Name:</label>
  <input type="text" id="nameInput"><br>

  <label for="score">Score:</label>
  <input type="text" id="scoresInput"><br>

  <label>&nbsp;</label>
  <input type="button" id="add" value="Add to Array" >
  <input type="button" id="display_results" value="Display Results" >
  <input type="button" id="display_scores" value="Display Scores" ><br>


  <div id="results">
    <h2 id="results_header"></h2>
    <p id="results_text"></p>	
  </div>
  <h2 id="scores_header"></h2>
  <table id="scores_table">
    <tr>
      <th id="names" align="left"></th>
      <th id="scores" align="left"></th>
    </tr>
  </table>
</main>

2 个答案:

答案 0 :(得分:0)

您没有初始化total,因此当您执行total = total + scores[i];时,Javascript会将其视为字符串。

只需在var total = 0功能

的开头写displayResults()即可

答案 1 :(得分:0)

可能是因为scoreInput是一个字符串(来自HTML输入的任何值),因此当您尝试将新分数添加到displayResults()中的旧分数时,它不是在添加数字,而是在结束串。首先尝试将输入转换为Number

var addScore = function() {
    var nameInput = $("nameInput").value;
    // convert score to a Number first...
    var scoreInput = Number( $("scoresInput").value );

    // make sure `scoreInput` is valid AND in range...
    if ((nameInput == "" || scoreInput == "") || ((!scoreInput && scoreInput !== 0)|| scoreInput < 0 || scoreInput > 100 )){
        alert("You must enter a name and a valid score");
    }
    else {
        names[names.length] = nameInput;
        scores[scores.length] = scoreInput;
    }
};

修改

正如@rpadovani所说,你也应该每次total内初始化displayResults()

var displayResults = function () {
    total = 0;

    // ... (the rest of your code)
};