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

如何将命令的消息args参数与.json文件内的menu数组元素做匹配

可行实现方案

原有代码存在两个问题:

  • args.toString().toLowerCase()未赋值,大小写转换逻辑不生效
  • 硬编码菜单索引的写法扩展性差,新增菜品需要手动修改分支

完整修改后代码

const Command = require("../Structures/Command.js");
const { menu } = require("../data/menu.json");

module.exports = new Command({
    name: "order",
    description: "Make an order",

    async run(message, args, client){
        // 校验是否输入了订单内容
        if (!args[1]) {
            return message.reply(`sorry, we either don't serve that here, or you didn't say what you want to order`);
        }
        // 统一转换为小写避免大小写匹配问题
        const userOrder = args[1].toLowerCase();
        // 检查订单是否在菜单中
        if (menu.includes(userOrder)) {
            // 特殊冠词处理可在这里加分支,比如tea前加a
            const prefix = userOrder === "tea" ? "a " : "";
            message.reply(`accepted your order for ${prefix}${userOrder}!`);
        } else {
            message.reply(`sorry, we either don't serve that here, or you didn't say what you want to order`);
        }
    }
})

扩展适配(可选)

如果存在多词菜品(比如ice coffee),可以将参数拼接后再匹配,替换const userOrder = args[1].toLowerCase()为:

const userOrder = args.slice(1).join(' ').toLowerCase();

这样可以支持多词的菜品名称识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:54:03