【问题标题】:How to dynamically add properties to an object in node.js?如何在node.js中为对象动态添加属性?
【发布时间】:2021-03-19 09:20:17
【问题描述】:

我有一个对象,我希望能够在其中动态添加至少一个属性。 属性的数量取决于我拥有的数组中的项目。 这是我引用的对象:

const helpEmbedMsg = new global.Discord.MessageEmbed()
                // Display a different (random) color every time the command is used.
                .setColor("RANDOM")
                .setTitle("Help")
                .setAuthor("Beatrice~")
                .setDescription("A full list of the commands available to you..")
                .addFields(
                    { name: `The current __prefix__ for this server is:   \`${prefix}\``, value: "\u200B" },
                )
                .addField("???? Here's a list of all my commands:", "\u200B", false)

                .addField("\u200B", "\u200B", false)
                .addField(`Type \`${prefix}help <command>\` to learn more about a command and it's usage!   `, `Example: \`${prefix}help ping\``, false)
                .setTimestamp()
                .setFooter(`Command triggered in ${message.channel.guild}`);

所以,基本上,如果数组的长度是4,我想添加以下内容:

.addField(array[i], "text here", true)

四次,但在对象中的特定位置(顺序很重要),就在这一行的正下方:

.addField("???? Here's a list of all my commands:", "\u200B", false)

【问题讨论】:

    标签: javascript node.js arrays object discord.js


    【解决方案1】:

    所以,只需将代码分成两条链,它们之间有一个for 循环:

    const helpEmbedMsg = new global.Discord.MessageEmbed();
    
    helpEmbedMsg.setColor("RANDOM")
        .setTitle("Help")
        .setAuthor("Beatrice~")
        .setDescription("A full list of the commands available to you..")
        .addFields(
            { name: `The current __prefix__ for this server is:   \`${prefix}\``, value: "\u200B" },
        )
        .addField("? Here's a list of all my commands:", "\u200B", false);
    
    // add an array of properties in this specific order
    for (let item of array) {
        helpEmbedMsg.addField(item, "text here", true);
    }
    
    // add the rest    
    helpEmbedMsg.addField("\u200B", "\u200B", false)
        .addField(`Type \`${prefix}help <command>\` to learn more about a command and it's usage!   `, `Example: \`${prefix}help ping\``, false)
        .setTimestamp()
        .setFooter(`Command triggered in ${message.channel.guild}`);
    

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 2014-05-29
      • 2020-11-05
      • 2017-09-20
      相关资源
      最近更新 更多