简体   繁体   中英

includes method not checking input against array in Javascript

First off, new to Javascript ... trying to write good code! As a test for the app I am writing, I want to have a user's name input via prompt checked against an array that will enable user to keep going or prevent user from doing so.

I can get includes to filter properly when I assign a value to a variable:

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!!");
}

returns "You may not enter!" However, when I include the function enabling the user to input a name,

    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 ();

any name the user inputs (including "bob" and "jim") returns "You have been granted access!" The includes function is being bypassed.

Am I missing an argument in either the enterName function or the denyEntry function?

You are redeclaring the Name inside function enterName() so its scope is limited to only that function. Make name global variable:

 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 (); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM