如何获得推送数组的总和

时间:2018-06-14 13:57:45

标签: javascript html arrays function

有人可以帮助我将数字推送到数组吗?我需要在20轮后显示总和。我推送由玩家输入的得分点数,所有得分需要在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>

1 个答案:

答案 0 :(得分: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>