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

discord.js导入数组后访问元素返回undefined问题

问题解决:导入数组后无法访问元素返回undefined

问题原因

你在standList.js中通过exports.stands导出数组,这意味着require导入的是一个包含stands属性的对象,而非数组本身。从控制台输出的{ stands: [ 'Star Platinum', 'Crazy Diamond', 'Golden Experience' ] }也能验证这一点——你直接用stands[0]访问的是对象的数字索引,对象没有这类索引,所以返回undefined。

解决方案

有两种方式可以解决这个问题:

方式一:解构导入数组

修改导入代码,直接提取对象中的stands数组:

const { stands } = require('../data/standList.js');

之后你就可以正常用stands[0]访问数组元素了。

方式二:通过对象属性访问数组

保持现有导入代码不变,访问时指定对象的stands属性:

var stand = stands.stands[0];

额外提示

你的代码里还有一个潜在问题:

if (interaction.customId = 'standarrow')

这里用了赋值运算符=,会把'standarrow'赋值给interaction.customId,导致这个条件永远为真。应该改成严格相等运算符===:

if (interaction.customId === 'standarrow')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:10:36