简体   繁体   English

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

[英]Can't read property 'name' of undefined

I've been getting an error along the lines of "Cannot read property 'name' of undefined" and the error traces back to this code我一直在收到“无法读取未定义的属性‘名称’”的错误,并且该错误可追溯到代码

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

What's going wrong here?这里出了什么问题?

slightly larger peice of code稍微大一点的代码

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)
}

Add an Elvis operator:添加一个 Elvis 运算符:

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

Or do it the old way:或者用旧的方式来做:

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

So you're getting this error because you're trying to access 'r.name' in your Array.find() method and some of the entries in the array appear to be 'undefined' or 'null'.因此,您收到此错误是因为您尝试访问 Array.find() 方法中的“r.name”,而数组中的某些条目似乎是“未定义”或“空”。 I would first run an Array.filter(r => !!r) and then chain on the .find() method afterwards to make sure all your entries are not undefined/null.我会首先运行一个 Array.filter(r => !!r) 然后在 .find() 方法上链接,以确保所有条目都不是未定义的/空的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM