检查输入值是否与数组项匹配

我有一些项目的数组,这些都是可能的密码,并且代码有效,但只能使用其中之一。如何使它与数组中的所有项目一起使用?


我尝试写if(input.value == password [0,1,2,3,4,5])但它不起作用


input1是文本字段的ID,button是按钮的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;

        }


    })


小唯快跑啊
浏览 174回答 3
3回答

慕雪6442864

一种可能的解决方案是for loop使用Array.includes()替换整个示例,例如:let password = new Array("pass1", "pass2", "pass3", "pass4", "pass5");let button = document.getElementById("button");let input = document.getElementById("input1");button.addEventListener("click", function(){&nbsp; &nbsp; if (password.includes(input.value))&nbsp; &nbsp; &nbsp; &nbsp; alert("welcome");&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; alert("wrong");});<input type="text" id="input1"><button type="button" id="button">Button</button>

MMMHUHU

您需要检查数组的元素,并在欢迎之后返回是否找到该值。在循环后将错误的警报置于末尾,因为对于每个不匹配的密码,您都会收到更多警报。button.addEventListener("click", function () {&nbsp; &nbsp; for (var x = 0; x <= password.length; x++) {&nbsp; &nbsp; &nbsp; &nbsp; if (input.value == password[x]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("welcome"); // or take document.getElementById('someid').innerHTML = 'welcome!'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; alert("wrong");});

温温酱

只需更换if (input.value == password[0])的if (input.value == password[x]),以检查迭代密码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript