【问题标题】:Checking if input value matches the array items检查输入值是否与数组项匹配
【发布时间】:2019-05-02 17:10:10
【问题描述】:

我有几个项目的数组,它们是可能的密码,并且代码有效,但仅适用于其中一个。我怎样才能使它与数组中的所有项目一起工作?

我试着写 if (input.value == 密码[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;
        }

    })

【问题讨论】:

  • 也许,您可以使用if (password.includes(input.value)) 代替loop

标签: javascript


【解决方案1】:

一种可能的解决方案是使用Array.includes() 替换整个for loop,例如:

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>

【讨论】:

    【解决方案2】:

    您需要检查数组的一个元素,如果找到该值,则在欢迎后返回。

    在循环结束后将错误的警报放在最后,因为每个不匹配的密码都会收到更多警报​​。

    button.addEventListener("click", function () {
        for (var x = 0; x <= password.length; x++) {
            if (input.value == password[x]) {
                alert("welcome"); // or take document.getElementById('someid').innerHTML = 'welcome!'
                return;
            }
        }
        alert("wrong");
    });
    

    【讨论】:

      【解决方案3】:

      您不需要循环来检查它。尝试indexOf 查找是否存在值:

      button.addEventListener("click", function () {
        if (passwords.indexOf(input.value) !== -1) {
          alert("welcome");
        } else {
          alert("wrong");
        }
      })
      

      【讨论】:

        【解决方案4】:

        只需将if (input.value == password[0]) 替换为if (input.value == password[x]) 即可检查迭代密码。

        【讨论】:

          【解决方案5】:

          试试这个:

          var passwords = ["pass1", "pass2", "pass3", "pass4", "pass5"];
          var input = document.getElementById("input1");
          var button = document.getElementById("button");
          
          button.addEventListener("click", function () {
            if (passwords.some(password => password === input.value)) {
              document.write("welcome");
            } else {
              alert("wrong");
            }
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-08-17
            • 2017-04-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多