首页 > 解决方案 > 如何制作 JS if 语句来查看值是否不是某些字符串?

问题描述

为什么这个 JS 不起作用?目标是在文本框中输入一些没有帮助的内容,windows-xp,显式,默认或什么都没有,按回车键,并发出警报“命令不存在”。

function checkInput() {
  var commandInput = document.getElementById("command-input")

  if (commandInput.value !== "help", "windows-xp", "explicit", "default", "") {
    alert("Command doesn't exist.");
  }

  event.preventDefault();

  document.getElementById("command-form").reset();
}
<form id="command-form">
  <input type="text" placeholder="Enter Command" id="command-input">
  <input type="submit" onclick="checkInput();" style="display: none;">
</form>

标签: javascripthtml

解决方案


使用Array.includes

const validCommands = ["help", "windows-xp", "explicit", "default", ""];

if (!validCommands.includes(commandInput.value)) {
  alert("Command doesn't exist.");
}

推荐阅读