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

Discord.js search命令中embed通过for in循环添加字段失效问题

问题根源

你用了for...in语法遍历数组results,for...in遍历数组时返回的是数组的索引字符串(比如"0"、"1"),而不是数组内的搜索结果对象。所以你拿到的result根本不是搜索结果,自然result.type、result.name等属性全是undefined,两个if判断都不触发,不会执行添加字段的逻辑。

修复方法

把循环语句替换成for...of即可,这是专门用来遍历可迭代对象(比如数组)元素的语法:

// 替换原来的for (const result in results)
for (const result of 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})
  }
}

额外优化建议

  • interaction.options.getString、interaction.options.getInteger都是同步方法,不需要加await调用,可以删掉前面的await减少不必要的异步等待。
  • 可以在循环前加判断,如果results是空数组,直接给embed加一个提示字段,说明没有匹配的搜索结果,避免返回只有标题描述的空embed。
  • 你提前声明的type2变量可以不用单独判断,直接用result.type首字母大写即可,和你现有逻辑效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:57:03