【问题标题】:Switch statement not working when using .includes()使用 .includes() 时切换语句不起作用
【发布时间】:2017-04-15 06:36:39
【问题描述】:
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 被调用时,带有字符串的消息变量应该通过 switch 语句运行,我有一个包含不同字符串的数组,如果消息包含来自该数组的字符串,则运行案例。但是什么都没有发生,一切似乎都正确,这里可能有什么问题?

【问题讨论】:

  • 仔细阅读switch 的文档。

标签: javascript node.js string switch-statement


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    switch 无法按您预期的方式工作。它采用 switch 中写入的值并与 case 块中的每个值进行比较。因此,在您的情况下,它会将真/假与值消息进行比较,并且找不到相同的值,因此不会发生任何事情。 您必须使用 if else 语句或解析消息并排除类似的值 消息“类型/表情 1” 将斜线后的所有内容提取并放入开关中

    【讨论】:

    • 我基本上想检查字符串message,如果字符串mesage包含emote[0],运行case语句。我使用 switch 语句,因为我必须再做大约 50 次,目前我只有 4 次,但在我知道它有效后我会添加 46 次。
    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多