[英]Javascript: Get the Index Value from an Array
这是我正在学习的Java脚本课程...
我需要创建一个简单的用户登录脚本。 页面加载后,会弹出提示询问用户名。 如果输入正确的用户名,则会显示另一个提示,要求输入密码。
如果用户名和用户名均有效,那么您将收到一条成功消息,否则您将收到一条失败消息。
我已经编写了所有代码,但是在验证用户名和密码时遇到了麻烦。 您可以在我的代码中看到我正在使用两个数组列表。 一个用于用户,另一个用于密码。 当我运行代码时,如果我输入user1的正确用户名和密码,它会验证;但是,如果我输入user1和user2的密码,它仍然会验证。
<script type="text/javascript">
//Input from user
var userId = prompt("Enter UserID", "");
userId_lowercase = userId.toLowerCase();
//Username and Password Arrays
var userIdList = new Array();
userIdList[0] = "user1";
userIdList[1] = "user2";
userIdList[2] = "user3";
var passwordList = new Array();
passwordList[0] = "pass1";
passwordList[1] = "pass2";
passwordList[2] = "pass3";
//Process input and check for authentication
//Check for correct userId
var userIdFound;
for (index in userIdList)
{
if (userId_lowercase == userIdList[index])
{
userIdFound = "Y";
break;
}
}
if (userIdFound == "Y")
{
document.write("<p>" + userId + " was Found</p>"); ;
//Check for correct Password
var password = prompt("Enter Password", "");
var passwordFound;
for (index in passwordList)
{
if (password == passwordList[index]) // This is where I need help,
// how do I say
// "if password is from the passwordList && it matches the userId index selected"
{
passwordFound = "Y";
break;
}
}
if (passwordFound == "Y")
{
document.write("<p>Welcome to the class!</p>");
}
else
{
document.write("<p>Error: Password is not valid.</p>");
}//END Password Check
}
else
{
document.write("<p>" + userId + " was NOT found</p>");
}//END USERID Check
</script>
而不是使用数组,而是将对象用作关联数组:
var Users = {
root: 'god',
fred: 'derf',
luser: 'password'
};
// you can access object properties using dot syntax:
User.root
// or using array syntax with a string as index
User['root'];
// when the name is stored in a variable, array syntax is the only option
var name='root';
User[name];
这是一项家庭作业,这是一件好事,否则由于内在的不安全感,我不得不给您一个笨拙的提示。
您还应该研究使用DOM API而不是过时的document.write
。
<script type="text/javascript">
...
function reportLogin(msg) {
var loginMsg = document.getElementById('LoginMsg');
if (loginMsg.firstChild) {
loginMsg.firstChild.nodeValue=msg;
} else {
loginMsg.appendChild(document.createTextNode(msg))
}
}
</script>
...
<p id="LoginMsg"></p>
要么
<script type="text/javascript">
...
function reportLogin(msg) {
document.getElementById('LoginMsg').firstChild.nodeValue=msg;
}
</script>
...
<p id="LoginMsg"> </p>
(请注意#LoginMsg
的空格。)
首先,我不会使用for-in,而是使用简单的for循环遍历数组。 然后,您可以存储与用户名匹配的索引,以将其与密码数组进行比较:
var index;
var userIndex;
for (index = 0; index < userIdList.length; index++) {
if (userId_lowercase == userIdList[index])
{
userIndex = index;
userIdFound = "Y";
break;
}
}
然后,在密码循环中,您会说:
if (password == passwordList[index] && index == userIndex)
{
passwordFound = "Y";
break;
}
这是解决问题的简单方法。 我不知道您学到了多少,但您也可以使用一系列对象:
var userLogins = [{user:"user1", password:"pass1"},...etc];
然后在询问名称和密码并查看它们是否匹配后循环遍历该数组:
for (index = 0; index < userLogins.length; index++) {
if (userLogins.user == userId_lowercase && userLogins.password == password) {
//Do stuff here
}
}
要记住的是,您必须以某种方式将用户名链接到密码。 您当前执行此操作的方式取决于两个数组中的索引,但这不能保证。 最好以某种方式链接这两部分信息,例如上面的对象数组。
这是我将使用哈希表(关联数组)的地方
var users = {
user1:"pass1",
user2:"pass2",
user3:"pass3"
};
现在您可以像这样测试:
function checkValidUser(userId, userPwd) {
return ( users[userId] == userPwd );
}
很简单。
您将需要对照密码检查用户名的索引。 一旦有了用户名,就将该索引保存到变量中,说indexOfUserName并对照密码数组检查该索引。 因此,请检查(Password == passwordList [indexOfUserName])是否是if(password == passwordList [index])
如果您想让老师后悔她的问题,请使用以下特殊版本:
var users = { user1:true, user2:true, user3:true },
pwds = {user1:'pw1', user2:'pw2', user3:'pw3'};
function theUser(userId){
return {
hasThePassword:function(pwd){
return users[userId] && pwds[userId] === pwd;
}
};
}
if( theUser( prompt('Enter UserID', '') ).hasThePassword( prompt('Enter Password', '') )){
alert('user ok');
}else{
alert('wrong user or password');
};
;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.