Cannot read property 'includes' of undefined

爱⌒轻易说出口 提交于 2019-12-20 04:33:14

问题


I am new to JavaScript, am I was trying to dissect an embedded message. Here's my code, it runs fine for a few mins, works accordingly but idk what goes wrong.

bot.on('message', (message) => {
  for (var i = 0; i < message.embeds.length; i++) {
    if (message.embeds[i].title.includes("text!")) {
      message.channel.send('reply')
    }
  }
})

回答1:


I think this code can fix this problem.


bot.on('message', (message) => {
  for (var i = 0; i < message.embeds.length; i++) {
    if (message.embeds[i] && message.embeds[i].title.includes("text!")) {
      message.channel.send('reply')
    }
  }
})




回答2:


Its because there is at least one item inside the embeds array items that missing the title property.

You will need to update the if statement to be:

If (message.embeds[i] &&
 message.embeds[i].title && ...)



回答3:


It means inside message.embeds[i] there is at least one element without title property.

You should check first if message.embeds[i].title exists and perform other operations after the check.




回答4:


You can write your code more defensive like this. Instead of

if(message.embeds[i].title.includes("text!"))

you can write the following

if(typeof message.embeds[i].title === "string" &&
message.embeds[i].title.includes("text!"))



回答5:


Probably some of the embed object is coming without the title property.

You can safely use your logic changing your if condition to:

if ('title' in message.embeds[i] && message.embeds[i].title.includes("text!")) {
   /* ... */
}


来源:https://stackoverflow.com/questions/55002942/cannot-read-property-includes-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!