简体   繁体   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 + " **");
});

When the function chat.on is called a variable of message with a string is supposed to run through the switch statement, I have an array with different strings and if the message includes a string from that array, run the case. 当将chat.on函数称为带有字符串的message变量应该通过switch语句运行时,我有一个包含不同字符串的数组,如果消息包含该数组中的字符串,请运行该案例。 But nothing happens, it all seems right what could be wrong here? 但是什么也没发生,这似乎是对的,这可能是错的?

switch doesn't work in the way you expect. 开关不能按您期望的方式工作。 It takes the value written in switch and compares with each in the case blocks. 它获取写入switch中的值,并与case块中的每个值进行比较。 So in your case it will compare true/false with the value message, and it won't find the same value and as a result nothing will happen. 因此,在您的情况下,它将把true / false与值消息进行比较,并且它将找不到相同的值,结果将不会发生任何事情。 You have to use if else statements or parse the message and exclude the value like Message 'type/emote1' Extract everything afte slash and put it in the switch 您必须使用if else语句或解析消息并排除消息'type / emote1'之类的值,然后在斜杠中提取所有内容并将其放入开关中

One way to solve this problem is by using switch(true) instead of switch(method). 解决此问题的一种方法是使用switch(true)而不是switch(method)。 This will work since then it will compare true(boolean) with the case statements. 这将起作用,因为它将比较true(boolean)与case语句。 The Case Statement which includes emote[0] will be returning true, thus it will go ahead and execute that block. 包含emote [0]的Case语句将返回true,因此它将继续执行该块。 I hope it helps. 希望对您有所帮助。

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

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