英文:
How to calculate correctly
问题
我尝试计算来自我的 Dapp 的投票。
但我不知道如何计算它们,以下是我目前拥有的代码:
useEffect(() => {
const fetchAllVotes = async () => {
const items = await fetchItems(); // 获取所有项目
const votesPerItem = await Promise.all(
items.map(async (item) => {
const votes = await getVotes(item.id); // 获取项目的所有投票
return votes;
})
);
const allVotes = votesPerItem.flat(); // 将所有投票合并为单个数组
setVotes(allVotes);
};
fetchAllVotes();
}, [])
votes.map((vote) => {
console.log(vote.toString());
})
我也尝试了这样缩减... 但我得到了第二张图片所示的结果:
const totalVotes = votes.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log("总投票数:", totalVotes);
英文:
I try to calculate votes from my Dapp.
But I dont know how to calculate them this is what i have so fare
useEffect(() => {
const fetchAllVotes = async () => {
const items = await fetchItems(); // get all the items
const votesPerItem = await Promise.all(
items.map(async (item) => {
const votes = await getVotes(item.id); // get all the votes for the item
return votes;
})
);
const allVotes = votesPerItem.flat(); // combine all the votes into a single array
setVotes(allVotes);
};
fetchAllVotes();
}, [])
votes.map((vote) => {
console.log(vote.toString());
})
I also tried to reduce like this.. But then i get the result like the second picture indicates
const totalVotes = votes.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log("Total votes:", totalVotes);
答案1
得分: 1
看起来你得到了一个string
数组。不要忘记将它们转换为integer
或float
:
const sum = votes.reduce((partialSum, a) => parseInt(partialSum) + parseInt(a), 0);
英文:
Looks like you are getting an array of string
. Don’t forget to convert them into integer
or float
:
const sum = votes.reduce((partialSum, a) => parseInt(partialSum) + parseInt(a), 0);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论