如何在node.js中为对象动态添加属性?
Posted
技术标签:
【中文标题】如何在node.js中为对象动态添加属性?【英文标题】:How to dynamically add properties to an object in 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 \`$prefixhelp <command>\` to learn more about a command and it's usage! `, `Example: \`$prefixhelp 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)
【问题讨论】:
【参考方案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 \`$prefixhelp <command>\` to learn more about a command and it's usage! `, `Example: \`$prefixhelp ping\``, false)
.setTimestamp()
.setFooter(`Command triggered in $message.channel.guild`);
【讨论】:
以上是关于如何在node.js中为对象动态添加属性?的主要内容,如果未能解决你的问题,请参考以下文章