繁体   English   中英

使用.includes()时,switch语句不起作用

[英]Switch statement not working when using .includes()

client.on('chat', function(channel, userstate, message, self){



  switch(message){
    case message.includes(emotes[0]):
      numberOfEmotes[0]++;
      console.log("Emote0 has been used " + numberOfEmotes[0] + " time(s)");
      break;
    case message.includes(emotes[1]):
      numberOfEmotes[1]++;
      console.log("Emote1 has been used " + numberOfEmotes[1] + " time(s)");
      break;
    case message.includes(emotes[2]):
      numberOfEmotes[2]++;
      console.log("Emote2 has been used " + numberOfEmotes[2] + " time(s)");
      break;
    case message.includes(emotes[3]):
      numberOfEmotes[3]++;
      console.log("Emote3 has been used " + numberOfEmotes[3] + " time(s)");
      break;
  }

/*  if(message.includes(emotes[0])){
    numberOfEmotes[0]++;
    console.log("Emote0 has been used " + numberOfEmotes[0] + " time(s)");
  }*/


  //console.log("** " + message + " **");
});

当将chat.on函数称为带有字符串的message变量应该通过switch语句运行时,我有一个包含不同字符串的数组,如果消息包含该数组中的字符串,请运行该案例。 但是什么也没发生,这似乎是对的,这可能是错的?

开关不能按您期望的方式工作。 它获取写入switch中的值,并与case块中的每个值进行比较。 因此,在您的情况下,它将把true / false与值消息进行比较,并且它将找不到相同的值,结果将不会发生任何事情。 您必须使用if else语句或解析消息并排除消息'type / emote1'之类的值,然后在斜杠中提取所有内容并将其放入开关中

解决此问题的一种方法是使用switch(true)而不是switch(method)。 这将起作用,因为它将比较true(boolean)与case语句。 包含emote [0]的Case语句将返回true,因此它将继续执行该块。 希望对您有所帮助。

暂无
暂无

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

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