一个函数,它将一组数字作为参数收集并返回一个百分比数组?

时间:2017-06-29 15:31:32

标签: javascript loops input

我目前是初学者,并试图了解如何基本上使用函数从每个输入中获取数字的数组,然后找出如何为每个候选人制作单独的百分比。在JS中,使用它来获得总数,但有没有办法以某种方式从每个输入中获取每个单独的数字?也许我用我的for循环进入了一个错误的方向:/任何方向或提示都会很棒。

<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>


<output id="totalvotes"></output>

这里是JS for it

function totalVotes() {
  var votes = document.getElementsByName("votesPerPerson");
  var totalVotes = 0;
  for( var i = 0; i < votes.length; i ++ ) {
  totalVotes += parseInt(votes[i].value);
}
 document.getElementById("totalvotes").innerHTML = totalVotes;
}

3 个答案:

答案 0 :(得分:1)

function totalVotes() {
  var votes = document.getElementsByName("votesPerPerson");
  var totalVotes = 0;
  var percentages = [];
  for( var i = 0; i < votes.length; i ++ ) {
    totalVotes += parseInt(votes[i].value);
    percentages[i] = parseInt(votes[i].value);
  }
  percentages = percentages.map(function(candidateVotes) {return candidateVotes/totalVotes;});
  document.getElementById("totalvotes").innerHTML = totalVotes;
}

百分比在同一个数组的数组中,然后你可以用它做任何你想做的事! 希望这会有所帮助!

答案 1 :(得分:1)

看起来你已经很好地掌握了总和。要创建一个数组,有几种方法可以做到,但我建议从这样的元素集合中映射它:

&#13;
&#13;
function totalVotes() {
  var votes = document.getElementsByName("votesPerPerson");
  var total = document.getElementById("totalvotes");
  // create new array
  var percentages = [];
  var totalVotes = 0;

  // reset innerHTML in case loop returns early due to invalid value
  total.innerHTML = "";
  
  // reset each vote percentage
  for (var i = 0; i < votes.length; i++) {
    votes[i].nextElementSibling.innerHTML = "";
  }

  // overwrite each index with value
  for (var i = 0; i < votes.length; i++) {
    totalVotes += percentages[i] = parseInt(votes[i].value);
    
    // one of the values is invalid
    if (isNaN(percentages[i])) return;
  }

  total.innerHTML = totalVotes;

  // calculate percentages here by mapping array of votes
  for (var i = 0; i < percentages.length; i++) {
    percentages[i] = 100 * percentages[i] / totalVotes;
    
    votes[i].nextElementSibling.innerHTML = percentages[i].toFixed(2) + "%";
  }
}

document.addEventListener('change', totalVotes)
&#13;
<div>
  <label for="votes1">Votes for Candidate 1</label>
  <input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
  <output></output>
</div>
<div>
  <label for="votes2">Votes for Candidate 2</label>
  <input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
  <output></output>
</div>
<div>
  <label for="votes3">Votes for Candidate 3</label>
  <input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
  <output></output>
</div>

<output id="totalvotes"></output>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你大多都有这个想法。你只需要附加一些事件处理程序(另外一个小的改动)。

&#13;
&#13;
function totalVotes() {
  var votes = document.getElementsByName("votesPerPerson");
  var totalVotes = 0;
  for(var i = 0; i < votes.length; i++) {
    totalVotes += parseInt(votes[i].value || 0); // "Minor change" here
  }
  document.getElementById("totalvotes").innerHTML = totalVotes;
}

// Additions below this point
var votes = document.getElementsByName("votesPerPerson");
for( var i = 0; i < votes.length; i ++ ) {
  votes[i].addEventListener('change', totalVotes);
}

totalVotes(); // Run once to get 0 to show without changing anything
&#13;
<div>
  <label for="votes1">Votes for Candidate 1</label>
  <input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
  <label for="votes2">Votes for Candidate 2</label>
  <input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
  <label for="votes3">Votes for Candidate 3</label>
  <input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>


<output id="totalvotes"></output>
&#13;
&#13;
&#13;

现在,该代码有效,但请注意一些重复,全局变量等。这里有一个替代方案可以为您提供一些不同的方法来完成相同的事情:

&#13;
&#13;
// If you want to know what this outer function is, look up "IIFE"
(function() {
  'use strict';

  // Get the elements (and make sure they are put in an array)
  var voteInputEls = Array.from(
    document.getElementsByName('votesPerPerson')
  );

  // This is used below to handle the change event
  function setTotalVotes() {

    // "reduce" the voteInputEls array to a total value
    var totalVotes = voteInputEls.reduce(function (lastVal, voteInputEl) {
      return lastVal + parseInt(voteInputEl.value || 0);
    }, 0);

    document.getElementById('totalvotes').innerHTML = totalVotes;
  }

  // Attach event listeners
  voteInputEls.forEach(function(voteInputEl) {
    voteInputEl.addEventListener('change', setTotalVotes);
  });
  setTotalVotes(); // Run once to get 0

})();
&#13;
<div>
  <label for="votes1">Votes for Candidate 1</label>
  <input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
  <label for="votes2">Votes for Candidate 2</label>
  <input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
  <label for="votes3">Votes for Candidate 3</label>
  <input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>


<output id="totalvotes"></output>
&#13;
&#13;
&#13;