简体   繁体   English

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

[英]A function that collects an array of numbers as a parameter and returns an array of percentages?

I'm currently a beginner and trying to understand how to basically use a function get an array of the numbers from each input to then figure out how to make an individual percentage for each candidate. 我现在是初学者并且试图理解如何基本上使用函数从每个输入中获取数字的数组,然后找出如何为每个候选者制作单独的百分比。 In the JS, using that to get the total but is there a way to get each individual number from each input somehow? 在JS中,使用它来获得总数,但有没有办法以某种方式从每个输入中获取每个单独的数字? Maybe I'm going into a wrong direction with my for loop :/ Any direction or hints would be great. 也许我的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>

Here's the JS for it 这是它的JS

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;
}
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;
}

The percentages are in the array of the same name, then you can do whatever you want with it! 百分比在同一个数组中,然后你可以用它做任何你想做的事! Hopes this helps! 希望这有帮助!

Looks like you have a good grasp of getting the sum. 看起来你已经很好地掌握了总和。 To create an array, there's several ways you can do that but I recommend mapping it from the collection of elements like this: 要创建一个数组,有几种方法可以做到,但我建议从像这样的元素集合中映射它:

 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) 
 <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> 

You mostly have the idea. 你大多有这个主意。 You just need to attach some event handlers (with one other minor change). 您只需要附加一些事件处理程序(另外一个小的更改)。

 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 
 <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> 

Now, that code works, but note some of the repetition, global variables, etc. Here's an alternative that may offer you some different ways of accomplishing the same things: 现在,该代码可以工作,但请注意一些重复,全局变量等。这里有一个替代方案可以为您提供一些不同的方法来完成相同的事情:

 // 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 })(); 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个从数组中收集值以作为参数传递的计数器? - how to create a counter that collects values from an array to pass as a parameter? function 返回一个数组,其中包含从 1 到 255 的所有数字 - function that returns an array with all the numbers from 1 to 255 返回奇数和空数组的函数 - Function that returns array with odd numbers and null 用参数 Function 过滤数组之间的数字 - Filter numbers between Array with Parameter Function 传递一个返回数组作为参数的函数 - Passing a function which returns array as a parameter 给定一组正数,负数和零数字,返回百分比数组 - Returning an array of percentages given an array of positives, negatives, and zero numbers 制作一个在数组中添加数字并在javascript中返回其总和的函数 - Making a function that adds numbers in an array and returns their sum in javascript 创建一个函数,返回一个包含5到118之间所有奇数的数组 - Create a function that returns an array with all the odd numbers from 5 to 118 如果该数字很大,为什么 function 会返回错误的数字数组 - Why function returns wrong array of numbers if that number is big 我需要编写一个遍历数字数组的函数,并在其数组中返回奇数和偶数。 - I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM