【问题标题】:How to make an error message when someone enters an invalid command当有人输入无效命令时如何发出错误消息
【发布时间】:2017-10-14 21:49:54
【问题描述】:

这个link 是我正在使用JSJquery 进行的顶针项目。我正在制作一个基于文本的游戏,我想知道是否有人可以帮助我显示错误消息,以便当有人键入不在函数中的命令时,它会在我的游戏中返回错误,并且不会在控制台中显示一个。

【问题讨论】:

  • 警报(消息); ?

标签: javascript jquery


【解决方案1】:

零代码和零了解您的应用的实际运行方式,这是我能给您的最好的。

// Create an array of acceptable commands
var commands = [
  "command1",
  "command2",
  "command3"
];

// Get the command typed into the game
var commandTyped = $("#command-line").val();


// Check if the command typed was in the array of acceptable commands
// If not do something
if( $.inArray( commandTyped, commands) == -1 ) {
  alert("That command doesn't exist");
}

【讨论】:

    【解决方案2】:
    var commands = [
      "command1",
      "command2",
      "command3"
    ];
    
    // Get the command typed into the game
    var commandTyped = $("#command-line").val();
    
    if (commands.indexOf(commandTyped) === -1) {
        alert('Invalid command!');
    }
    

    indexOf 将确保浏览器兼容性。当列表不包含项目时返回 -1。

    或者,您可以使用includes()

    if (commands.includes(commandTyped)) { ...

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多