-1

有人可以帮我将推送数字的总和放入数组吗?我需要在第 20 轮之后显示总和。我推的是玩家输入的 scorePoint,所有分数都需要在 20 轮后相乘才能看到结果。

var round = 1;
var score1 = [];

function roundNr() {
  round++;
  document.getElementById("p").innerHTML = round;
}

function scoreCntr() {
  var scorePoint1 = document.getElementById('score1').value;
  score1.push(scorePoint1);

  if (round > 20) {
    document.getElementById("score").innerHTML = score1;
  }
}
<div class="input_box">
  <input type="name" placeholder="Name" id="name1">
  <input type="text" placeholder="Score" id="score1">
  <button onclick="roundNr(); scoreCntr();">Submit</button>
</div>

<div class="round_box">
  <h1>ROUND</h1>
  <p id="p">1</p>
</div>

<div id="score">

</div>

4

1 回答 1

1

score1.forEach(val=>sum+=parseInt(val));在将计算总和的if条件中丢失。另请注意,当您推送值时,它是字符串类型,因此您需要parseInt()在添加它们之前使用获取整数值。

var round = 1;
var score1 = [];

function roundNr() {
  round++;
  document.getElementById("p").innerHTML = round;
}

function scoreCntr() {
  var scorePoint1 = document.getElementById('score1').value;
  score1.push(scorePoint1);

  if (round > 20) {
    var sum = 0;
    score1.forEach(val=>sum+=parseInt(val));
    document.getElementById("score").innerHTML = sum;
  }
}
<div class="input_box">
  <input type="name" placeholder="Name" id="name1">
  <input type="text" placeholder="Score" id="score1">
  <button onclick="roundNr(); scoreCntr();">Submit</button>
</div>

<div class="round_box">
  <h1>ROUND</h1>
  <p id="p">1</p>
</div>

<div id="score">

</div>

于 2018-06-14T14:02:29.027 回答