繁体   English   中英

Node.js - 根据用户输入访问数组中的项目

[英]Node.js - Access items from array based on user input

有人可以指出我做错了什么吗? 该程序应该允许我使用 discord 命令: C!发送报价(数字)(用户名)到 select 列表中的一个特定报价并将其作为消息发送。

msg.channel.send(`${quotes.quote[args[1]]}`);

这条线给我带来了最大的麻烦。 其他一切正常,但是当我输入命令 (C:send quote 17 Username) 程序崩溃并出现错误:
msg.channel.send( ${quotes.quote[args[1]]} );
TypeError:无法读取未定义的属性(读取“17”)

const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client();

    const quotes = [
        {
            id: "1",
            quote: "This is quote 1"
        },
        {   
            id: "2",
            quote: "This is quote 2"
        },
        {
            id: "3",
            quote: "This is quote 3"
        },
        {
            id: "4",
            quote: "This is quote 4"
        },
        {
            id: "5",
            quote: "This is quote 5"
        },
];

    client.on('message', (msg) => {
        if (msg.content.startsWith("C!send")) {
            let messageArray = msg.content.split(" ");
            let args = messageArray.slice(1)
            if (!args[0]) {
              return msg.channel.send("Error, missing argument 1");         
            } else if (args[0] === "quote") {
                if (!isNaN(args[1])) {
                   if (args[2] === undefined) {
                       return msg.channel.send("Erorr, missing argument 3");
                   } else {
                       msg.channel.send(`${quotes.quote[args[1]]}`); //This is where the program crashes
                   }
                } else {
                    return msg.channel.send("Error, argument 2 needs to be a number!");
                }
        }

}

这条线给了我

在您的代码quotes中是一个数组。 ${quotes.quote[args[1]]}中,您试图访问不存在的quotesquote属性。

试试这个:

`${quotes.find(i => i.id === args[1]).quote}`

如果您没有事先检查报价是否存在:

`${quotes.find(i => i.id === args[1])?.quote || "Quote not found"}`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM