我的搜索命令中的嵌入无法正常工作

The embed in my search command isn't working properly

在此 search 命令中,for in 循环未将字段添加到嵌入中。当我使用该命令时,我得到了我在创建嵌入时定义的名称和描述。但是我没有得到我在 for in 循环中添加的字段。

这是返回的图像,以防它有助于回答我的问题:

我的search命令代码:

const { MessageEmbed } = require('discord.js')

module.exports = {
    name: 'search',
    description: 'Searches for a song and returns the results.',
  options: [
    {
      name: 'search_term',
      description: 'The song to search for.',
      type: 'STRING',
      required: true
    },
    {
      name: 'limit',
      type: 'INTEGER',
      description: 'Number of results to return.',
      required: true
    },
    {
      name: 'type',
      type: 'STRING',
      description: 'The type of search result.',
      required: true,
      choices: [{
        name: 'Video',
        value: 'video'
      },
      {
        name: 'Playlist',
        value: 'playlist'
      }]
    }
  ],
    async execute(interaction) {
    const query = await interaction.options.getString('search_term')
    const limit = await interaction.options.getInteger('limit')
    const type = await interaction.options.getString('type')

    let type2 = 'x'
    if (type === 'video') type2 = 'Video'
    else if (type === 'playlist') type2 = 'Playlist'

    let results = await interaction.client.distube.search(query, { limit: limit, type: type })

    let embed = new MessageEmbed()
    .setTitle('search')
    .setDescription('Searches for a song and returns the results.')

    for (const result in results) {
      if (result.type === 'video') {
        embed.addFields({
          name :result.name, 
          value: `ID: ${result.id}\nType: ${type2}\nURL: ${result.url}\nViews: ${result.views}\nDuration: ${result.formattedDuration}\nLive: ${result.isLive}`, 
          inline: true})
      }
      else if (result.type === 'playlist') {
        embed.addFields({
          name: result.name, 
          value: `ID: ${result.id}\nType: ${type2}\nURL: ${result.url}\nViews: ${result.views}`,
          inline: true})
      }
    }

    await interaction.reply({embeds: [embed]})
    

    },
};

您需要使用 embed.addField(...) 或将数组传递给 embed.addFields([...])

<MessageEmbed>.addFields() 将数组作为输入。

解决方法:使用for of代替for in

两者的区别:

for...of 语句创建一个循环迭代可迭代对象,包括:内置StringArray、类数组对象(例如,参数或 NodeList)、TypedArrayMapSet

for...in 语句遍历对象的所有可枚举属性,这些属性由字符串键入(忽略由符号键入的属性),包括继承的可枚举属性。

更多信息:

for of: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

for in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in