gpt4 book ai didi

javascript - 一个收集数字数组作为参数并返回百分比数组的函数?

转载 作者:行者123 更新时间:2023-11-29 11:02:26 24 4
gpt4 key购买 nike

我目前是一名初学者,我试图了解如何从根本上使用一个函数从每个输入中获取一组数字,然后弄清楚如何为每个候选人计算一个单独的百分比。在 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

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

关于javascript - 一个收集数字数组作为参数并返回百分比数组的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44829392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com