我有一个由几个项目组成的数组,这些项目可能是密码,并且代码可以工作,但只能使用其中一个。我怎样才能让它与数组中的所有项目一起工作?
我试着写 if (input.value == 密码[0, 1, 2, 3, 4, 5]) 但这行不通
input1 是文本字段的 id, 按钮是按钮的ID, 这是脚本:
var password = new Array("pass1", "pass2", "pass3", "pass4", "pass5");
var input = document.getElementById("input1");
var button = document.getElementById("button");
button.addEventListener("click", function () {
for (var x = 0; x <= password.length; x++) {
if (input.value == password[0]) {
document.write("welcome");
break;
} else
alert("wrong");
break;
}
})
最佳答案
一种可能的解决方案是使用 Array.includes() 替换整个 for 循环
,例如:
let password = new Array("pass1", "pass2", "pass3", "pass4", "pass5");
let button = document.getElementById("button");
let input = document.getElementById("input1");
button.addEventListener("click", function()
{
if (password.includes(input.value))
alert("welcome");
else
alert("wrong");
});
<input type="text" id="input1">
<button type="button" id="button">Button</button>
关于javascript - 检查输入值是否与数组项匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55957237/