关于javascript:如何获得推送数组的总和

How to get sum of pushed array

本问题已经有最佳答案,请猛点这里访问。

有人能帮我把被推的数字和到数组中吗?我需要在20回合后显示总数。我按记分单,这是由球员键入,所有的分数需要乘以20轮后才能看到结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
  }
}
1
2
3
4
5
6
7
8
9
  <input type="name" placeholder="Name" id="name1">
  <input type="text" placeholder="Score" id="score1">
  <button onclick="roundNr(); scoreCntr();">Submit</button>



  ROUND
  <p id="p">1
</p>


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
  }
}
1
2
3
4
5
6
7
8
9
  <input type="name" placeholder="Name" id="name1">
  <input type="text" placeholder="Score" id="score1">
  <button onclick="roundNr(); scoreCntr();">Submit</button>



  ROUND
  <p id="p">1
</p>