如何修复错误无法读取未定义的属性“ trim”

时间:2019-12-15 19:49:15

标签: javascript discord discord.js

代码:

case `prefix`:
    var prfx = args[3];
    if (!prefix) return msg.reply(`prefix ?`);
    data.prefix = prfx.trim();
    msg.channel.send(`done , my prefix now is : ${prfx}`);
break;

错误:

TypeError: Cannot read property 'trim' of undefined at Client.client.on.msg

2 个答案:

答案 0 :(得分:1)

在您的情况下,prfx是未定义的,但是您正在检查变量prefix,并且仅在该变量为假时返回。您还必须检查prfx或只检查它。

case `prefix`:
   var prfx = args[3];
   if (!prefix || !prfx) { // Check for prfx as well, since that one could be undefined, maybe !prefix is not even needed or just mispelled
      return msg.reply(`prefix ?`);
   }
   data.prefix = prfx.trim();
   msg.channel.send(`done , my prefix now is : ${prfx}`);
   break;

答案 1 :(得分:0)

args [3]在args数组中为null或未定义。您应该在修整前检查它。

 case `prefix`:
   var prfx = args[3];
   if (!prfx) { // prfx is not null or undefined?
     throw 'prfx is null or undefined'; // throw an exception
   }
   data.prefix = prfx.trim();
   msg.channel.send(`done , my prefix now is : ${prfx}`);
   break;