如何正确计算

huangapple go评论65阅读模式
英文:

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数组。不要忘记将它们转换为integerfloat

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

huangapple
  • 本文由 发表于 2023年2月24日 01:12:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定