无法读取未定义的属性“名称”

时间:2020-10-16 14:20:57

标签: javascript node.js discord discord.js undefined

我在“无法读取未定义的属性'名称'”的行中遇到错误,该错误可追溯到代码

const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));

这是怎么回事?

稍大的代码段

if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send(`You do not have MANAGE_ROLES permission`)
try {
    const user = message.mentions.users.first();
    const member = message.guild.member(user);
    const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
    //after this i create a discord embed, give the member the role specified then send the embed.
} catch (err) {
    console.log(err)
}

2 个答案:

答案 0 :(得分:0)

添加猫王操作员:

const roleName = message.guild.roles.cache.find(r => 
  (r?.name === args[1].toString()) 
  || (r?.id === args[1].toString().replace(/[^\w\s]/gi, ''))
);

还是用旧方法做:

const roleName = message.guild.roles.cache.find(r => 
  r 
  && (r.name === args[1].toString()) 
  || (r.id === args[1].toString().replace(/[^\w\s]/gi, ''))
);

答案 1 :(得分:0)

因此,由于尝试访问Array.find()方法中的“ r.name”,并且数组中的某些条目似乎为“未定义”或“空”,因此出现了此错误。我首先要运行Array.filter(r => !! r),然后在.find()方法上进行链接,以确保所有条目都未定义/为空。