首先,Javascript 新手...尝试编写好的代码! 作为对我正在编写的应用程序的测试,我希望通过提示检查用户名输入的数组,这将使用户能够继续或阻止用户这样做。
当我为变量赋值时,我可以正确过滤包含内容:
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,因此其范围仅限于该函数。使 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 ();
关于javascript - 包含不检查 Javascript 数组输入的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50880328/