【问题标题】:How to get sum of pushed array [duplicate]如何获得推送数组的总和[重复]
【发布时间】:2018-11-24 08:05:10
【问题描述】:

有人可以帮我将推送数字的总和放入数组吗?我需要在第 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>

【问题讨论】:

  • 你有一个字符串数组,不是数字,而是:stackoverflow.com/questions/1230233/…
  • score1.push(+scorePoint1); ...innerHTML = score1.reduce((a, b) =&gt; a + b, 0);
  • 非常感谢!我是javascript的学生,所以我不知道。但无论如何感谢您的信息。

标签: javascript html arrays function


【解决方案1】:

您在将计算总和的if 条件中缺少score1.forEach(val=&gt;sum+=parseInt(val));。另请注意,当您推送值时,它是字符串类型,因此您需要在添加之前使用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>

【讨论】:

    猜你喜欢
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2013-04-22
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多