作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我试图做出一个具有多种可能性的 if 语句,但最终发生的事情是现在我有太多的 ||
在我的“如果”中。
我想也许可以将所有可能的值放入一个数组中,然后只执行condition == array
或其他什么。
无论如何,这是我的代码。请帮忙。提前致谢。
<body>
<input id="userInput">
<button onclick="Submit()">Submit</button>
<script>
function Submit() {
var input = document.getElementById("userInput").value;
if (input == "random text" || input == 3 || input == "more random text"
|| input == false || input == "another random string.")
{
// Do Something
}
</script>
</body>
最佳答案
您可以使用Array#includes或Array#indexOf并检查输入是否包含在您的数组中,其中您将允许的字符串(或其他类型 - 取决于您的输入类型)列入白名单
包含演示
let arr = ['random text', '3', 'more random test', 'lorem ipsum'];
function submit() {
input = document.getElementById("userInput").value;
if(arr.includes(input)) {
alert('yaaay that was easy');
}
}
<input id="userInput">
<button onclick="submit()">Submit</button>
关于javascript - JavaScript 中的 If(条件 == 任意数组值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49732157/
我是一名优秀的程序员,十分优秀!