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

遍历数组时返回整个数组而非单个元素的技术问题求助

问题分析与解决办法

问题根源

你在函数里使用了剩余参数...channels,但调用sendFreeGames时直接传入了完整的数组(比如sendFreeGames(yourAxiosResponseArray))。这会导致剩余参数将整个数组作为单个元素存入channels,最终channels变成了嵌套数组[yourAxiosResponseArray]。所以循环中的channel变量实际指向原数组,而非单个Axios响应对象,自然channel.data返回undefined,而channel[0].data能正常访问。

两种解决方式

方式一:调用函数时展开数组

保持函数参数不变,调用时用扩展运算符将数组元素逐个传入:

// 假设你的Axios响应数组是axiosResponses
sendFreeGames(...axiosResponses);

这样剩余参数...channels会单独接收数组的每个元素,循环里的channel就是单个Axios响应对象,channel.data.type可正常获取。

方式二:修改函数参数,移除剩余运算符

如果调用时必须传入完整数组,直接去掉参数的...:

/**
 * @param {Interaction[]} channels
 */
async sendFreeGames(channels) {
    const games = await this.#createEpicFreeGamesEmbeds();
    const buttons = await this.#createEpicFreeButtons();

    if (games.length === 0) return;

    for (const channel of channels) {
        // @ts-ignore
        const discordAxios = axios.create({ baseURL: 'https://discord.com/api/v10', headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}`,},});
        console.log(channel.data.type)
        discordAxios.post(`/channels/${channel.data.id}/messages`, { embeds: games, components: buttons });
    }
}

此时channels直接接收传入的数组,循环遍历就能拿到单个元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:08:14