var usernames = ["smith", "tron", "ace", "ladyj", "anon"];
var passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];
var x = prompt("Please enter the username");
var y = prompt("Please enter the password");
function validate(usernames, passwords) {
for (var i=0; i <usernames.length; i++) {
if ((x == usernames[i]) && (y == passwords[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Valid Credentials");
} else {
alert("Invalid Credentials")
}
}
因此,我尝试创建一个检查用户名并通过输入的提示进行传递的循环,因此基本上在提示输入用户名且用户输入“ smith”时,正确的密码应为“ qwerty”或用户输入“ tron”,用户输入的正确密码应为“ EndOfLine”,否则将弹出提示“无效凭据”的警报。
打开HTML文件时,我输入了用户名/密码,但输入凭据后未发送任何类型的警报。
答案 0 :(得分:0)
您有几处错误:
validate(usernames, passwords)
从未被调用valid
必须在函数外部声明这应该有效。
var usernames = ["smith", "tron", "ace", "ladyj", "anon"];
var passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];
var x = prompt("Please enter the username");
var y = prompt("Please enter the password");
var valid = false;
validate(x, y);
function validate(username, password) {
for (var i=0; i <usernames.length; i++) {
if ((username == usernames[i]) && (password == passwords[i])) {
valid = true;
break;
}
}
}
if(valid) {
alert("valid credentials");
}
else {
alert("invalid credentials");
}
另外,请不要在客户端保存密码
答案 1 :(得分:0)
除了将数组移到<script>
标记中并在某个地方调用validate()
之外,最好让它返回结果,而不是直接设置变量。如果循环中有匹配项,则此函数返回true
,如果没有匹配项,则该函数最后返回false
:
var usernames = ["smith", "tron", "ace", "ladyj", "anon"];
var passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];
function validate(username, password) {
for (var i=0; i <usernames.length; i++) {
if ((username === usernames[i]) && (password === passwords[i])) {
return true; // match found
}
}
return false; // match not found
}
var x = prompt("Please enter the username");
var y = prompt("Please enter the password");
var valid = validate(x, y);
if(valid) {
alert("valid credentials");
}
else {
alert("invalid credentials");
}
此外,在JavaScript
中,===
应该用作基本比较(对于相等,对于不平等,!==
)。较短的==
和!=
会进行各种隐式对话(请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators),一开始可能要避免。