DiscordJS v14:如何移除命令列表末尾的多余逗号?
Discord.js v14 帮助菜单下拉选择后命令列表末尾出现多余逗号的解决方案
问题根源
你的interactionCreate事件处理代码中,命令列表的生成逻辑存在缺陷:
先将符合条件的文件名用join(" ")拼接成字符串,再通过.split(".js")拆分,这会导致拆分后的数组最后多出一个空字符串元素。当这个数组直接转为字符串时,空元素就会表现为末尾的多余逗号。
举个例子:
假设文件夹内有kick.js和ban.js两个文件,经过join(" ")后得到字符串"kick.js ban.js",再用.split(".js")拆分,得到数组["kick ", " ban ", ""]。数组默认转字符串时用逗号分隔,最终就会变成kick , ban , ,出现多余逗号。
修复方案
以下两种方法都可以解决问题,任选其一即可:
方法一:直接移除文件名后缀(推荐)
直接对每个文件名做处理,去掉.js后缀,再按需拼接:
const commands = fs .readdirSync(`./commands/${selection}`) .filter((file) => file.endsWith(".js")) .map(file => file.replace(".js", "")); // 移除.js后缀
然后在Embed的描述中,用你想要的分隔符拼接数组(比如空格或逗号):
.setDescription(`\`\`\`${commands.join(", ")}\`\`\``)
方法二:过滤拆分后的空元素
如果不想修改前面的逻辑,可以在拆分后过滤掉空字符串:
const commands = fs .readdirSync(`./commands/${selection}`) .filter((file) => file.endsWith(".js")) .join(" ") .split(".js") .filter(item => item.trim() !== ""); // 过滤空元素
修改后的完整interactionCreate代码
const { Client, ChatInputCommandInteraction, InteractionType, EmbedBuilder } = require("discord.js"); const fs = require("fs"); module.exports = { name: "interactionCreate", async execute(interaction, client) { if (interaction.isSelectMenu) { if (interaction.customId === "helpMenu") { const selection = interaction.values[0]; // 使用方法一的处理逻辑 const commands = fs .readdirSync(`./commands/${selection}`) .filter((file) => file.endsWith(".js")) .map(file => file.replace(".js", "")); function capitalizeFL(str) { const capitalized = str.charAt(0).toUpperCase() + str.slice(1); return capitalized; } const embed = new EmbedBuilder() .setTitle(`Command list for ${selection}`) .setDescription(`\`\`\`${commands.join(", ")}\`\`\``) .setColor("Blurple") .addFields({ name: `Command Count`, value: `${commands.length} command(s)`, // 无需再减1 }); await interaction.reply({ embeds: [embed], ephemeral: true, }); } } }, };
内容的提问来源于stack exchange,提问作者Roman Beard
相关产品推荐
相关产品推荐

