错误:类型错误:无法读取未定义的属性“forEach”

时间:2021-04-26 22:05:06

标签: javascript discord discord.js

完整代码:

const Discord = require('discord.js');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION"]});

client.commands = new Discord.Collection()
client.events = new Discord.Collection()

['command', 'event'].forEach(handler =>{
    require(`./handlers/${handler}`)(client, Discord)
});

client.login('tokenremoved')

1 个答案:

答案 0 :(得分:2)

这个错误其实是“自动分号注入”造成的。如果您没有在代码中放置分号,Javascript 会尽其所能在底层添加分号。这是非常准确的,但是,有一些像这样的例子,它误解了所写的内容。

// javascript sees this:
client.events = new Discord.Collection()

['command', 'event'].forEach(handler =>{
    require(`./handlers/${handler}`)(client, Discord)
});

// and translates it to this:
client.events = new Discord.Collection()['command', 'event'].forEach(handler =>{
    require(`./handlers/${handler}`)(client, Discord)
});

Javascript 认为您正在尝试使用括号访问 Discord.Collection() 之外的参数。但是,由于 Collection#command 不存在,它返回 undefined。因此:

<块引用>

TypeError: 无法读取未定义的属性 'forEach'

const test = 'hello'

[true, 123].forEach(() => 'this throws an error')

解决办法就是在Discord.Collection()后加一个分号