You need to enable JavaScript to run this app. 如何访问Discord bot拉取消息返回的Collection [Map]中的第二个元素
优惠活动
大模型
产品
解决方案
定价
更多

如何访问Discord bot拉取消息返回的Collection [Map]中的第二个元素

问题原因

你调用Discord消息拉取接口返回的Collection是Discord.js对原生Map类的扩展,不属于普通JS对象:

  • Object.keys()只能读取普通对象自身的可枚举属性,无法读取Map中存储的键值对的键
  • Map/Collection结构不能用方括号[]直接按键取值,需要调用内置的.get()方法传入键获取对应值
正确获取第二个元素的方法

方法1:使用Collection内置at()方法(Discord.js v14+ 推荐)

Collection自带支持按索引取值的at()方法,索引从0开始计数,第二个元素对应索引1:

const mensajes = await message.channel.messages.fetch({ limit: 3 });
const secondMsg = mensajes.at(1);
console.log(secondMsg);

方法2:转数组后按索引取值(兼容所有版本)

可以先把Collection的value集合转为数组,再按索引取第二个元素:

const mensajes = await message.channel.messages.fetch({ limit: 3 });
const msgArray = [...mensajes.values()];
const secondMsg = msgArray[1];
console.log(secondMsg);

方法3:先取键集合再调用get()取值

如果你需要先拿到对应消息ID再取值,可以用这个方法:

const mensajes = await message.channel.messages.fetch({ limit: 3 });
const msgIds = [...mensajes.keys()];
const secondMsg = mensajes.get(msgIds[1]);
console.log(secondMsg);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 08:24:00