簡體   English   中英

包括不檢查Javascript中數組輸入的方法

[英]includes method not checking input against array in Javascript

首先,是Java語言的新手...嘗試編寫好的代碼! 作為對我正在編寫的應用程序的測試,我希望通過提示符對通過數組輸入的用戶名進行檢查,該數組將使用戶能夠繼續前進或阻止用戶這樣做。

當我給變量賦值時,我可以得到包含以正確過濾:

var name, excluded_Persons;
var name = "jim"

function denyEntry () {

var excluded_Persons = ["bob", "jim"];

    if (excluded_Persons.includes(name)) {
    alert("You may not enter!!");
    enterName ();
    }

    else {
        allowEntry ();
    }
}
denyEntry ();

function allowEntry () {

    alert("You have been granted access!!");
}

返回“您可能無法輸入!” 但是,當我包含允許用戶輸入名稱的功能時,

    var name, excluded_Persons;

function enterName () {
    var name = prompt("What is your name?").toLowerCase();
    }

enterName ();

function denyEntry () {

    var excluded_Persons = ["bob", "jim"];

    if (excluded_Persons.includes(name)) {
    alert("You may not enter!!");
    enterName ();
    }

    else {
        allowEntry ();
    }

}

denyEntry ();

用戶輸入的任何名稱(包括“ bob”和“ jim”)都將返回“您已被授予訪問權限!” 包含功能被繞過。

我是否在enterName函數或denyEntry函數中缺少參數?

您在函數enterName()中重新聲明了Name,因此其范圍僅限於該函數。 將名稱設為全局變量:

 var name, excluded_Persons; function enterName () { name = prompt("What is your name?").toLowerCase(); } enterName (); function denyEntry () { var excluded_Persons = ["bob", "jim"]; console.log(name); if (excluded_Persons.includes(name)) { alert("You may not enter!!"); enterName (); } else { allowEntry (); } } denyEntry (); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM