You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确计算Dapp中的投票数?

Dapp投票数计算异常问题

我正在尝试计算Dapp中的投票数,但使用reduce求和时得到的是字符串拼接结果,而非正确的数值总和。

当前代码实现

投票数据获取逻辑

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("Total votes:", totalVotes);

问题现象

控制台能正常打印出单个投票的数值,但求和结果是字符串拼接(比如投票值为"1"、"2"时,总和为"012"而非3)。

问题原因

从接口获取的投票数据是字符串类型,JavaScript中+运算符遇到字符串会触发拼接逻辑,而非数值加法,导致最终结果异常。

解决方法

方案1:在求和时转换类型

直接在reduce回调中将当前投票值转为数值:

const totalVotes = votes.reduce((accumulator, currentValue) => {
    return accumulator + Number(currentValue);
}, 0);

方案2:提前统一转换数组类型

在获取投票数据后,先将所有投票值转为数值再存入状态,后续求和逻辑无需修改:

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.map(vote => Number(vote));
            })
        );
        const allVotes = votesPerItem.flat();
        setVotes(allVotes);
    };
    fetchAllVotes();
}, [])

方案3:使用整数/小数解析函数

如果投票值是整数,可使用parseInt;如果是带小数的数值,用parseFloat:

// 整数场景
const totalVotes = votes.reduce((accumulator, currentValue) => {
    return accumulator + parseInt(currentValue, 10); // 第二个参数指定十进制解析
}, 0);

// 小数场景
const totalVotes = votes.reduce((accumulator, currentValue) => {
    return accumulator + parseFloat(currentValue);
}, 0);

内容的提问来源于stack exchange,提问作者bela jonas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:27:21