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

Discord.js v13:使用forEach限制Trello-node-api结果数量时出现重复问题

解决Trello Node API结果超过5条时重复输出的问题

你的代码出现重复输出的核心原因是:当符合条件的条目数超过5时,你在i > 5的分支里循环了5次,每次都添加当前element的字段,导致重复插入同一条内容。

正确的逻辑应该是先筛选出所有符合条件的卡片,再只取前5条生成Embed字段,最后根据总数量判断是否显示剩余条数。以下是修正后的代码:

trelloNode.board.searchCards("tOmOukAB").then(function(response) {
    // 先筛选出符合条件的卡片
    const filteredCards = response.filter(element => 
        element.name.includes(id) && element.idList === myListId
    );

    const totalBans = filteredCards.length;

    if (totalBans === 0) {
        const embed2 = new MessageEmbed()
            .setColor("#FF0505")
            .setDescription(`**${username2}** isn't banned!`);
        return interaction.reply({ embeds: [embed2] });
    }

    // 只处理前5条卡片
    filteredCards.slice(0, 5).forEach((card, index) => {
        const date = new Date(card.due);
        embed.addField(
            `Ban ${index + 1}`,
            `Due: [${new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }).format(date)}](${card.url})\n${card.desc}`,
            true
        );
    });

    // 设置剩余条数的footer
    if (totalBans > 5) {
        embed.setFooter({ text: `${totalBans - 5} more ban(s)...` });
    }

    return interaction.reply({ embeds: [embed] });
});

关键修正点:

  • 用filter先筛选符合条件的卡片,避免在循环里嵌套多层判断,逻辑更清晰
  • 用slice(0,5)直接截取前5条,不需要通过i计数判断,从根源避免重复添加
  • 提前计算总条数,直接用总条数减去5得到剩余数量,逻辑更简洁
  • 把无结果的判断放在最前面,减少嵌套层级

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:33:46