2010-02-12 119 views
1

这是针对正在采取的Java脚本课程...Javascript:从数组获取索引值

我需要创建一个简单的用户登录脚本。当页面加载提示时弹出询问用户名称。如果输入正确的用户名,则会显示另一个提示,要求输入密码。

如果用户名和有效,那么你一个成功的消息,否则你会得到一个失败的消息。

我写了所有的代码,但在验证用户名和密码时遇到了问题。 你可以在我的代码中看到我正在使用两个数组列表。一个用于用户,另一个用于密码。当我运行我的代码时,如果我为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> 
+1

登录形式很容易被欺骗。 “功课”让你感觉如此不切实际,这真让人遗憾。 –

+0

@NSfY:顺便说一句,谢谢你让我们知道这是一个家庭作业问题。实际上没有人这样做。 – outis

回答

2

首先,我不会使用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 
    } 
} 

需要记住的是,您必须以某种方式将用户名连接到密码。你目前这样做的方式是通过两个数组中的索引,但这并不能保证。以某种方式链接两位信息会更好,如上面的对象数组。

+0

我非常感谢您传授您的知识。这帮助了一大堆。我一直有循环问题。在这些项目上工作真的帮助我理解他们。 我同意很多人提到过使用Javascript来验证用户身份。但是这个项目帮助我理解了如何处理数组和循环。 再次,你们摇滚! 顺便说一句 - StackoverFlow社区是最好的! – NoDinero

2

而不是使用数组,使用对象作为关联数组:

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]; 

这是一件好事,这是家庭作业,否则我将不得不与cluefulness的板揍你由于固有的不安全。

您还应该考虑使用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的空间。)

0

您需要核对密码的用户名的索引。一旦你有用户名保存索引到变量说indexOfUserName并检查该索引对您的密码数组。因此,而不是如果(密码== passwordList [指数])检查,如果(密码== passwordList [indexOfUserName])

1

这里是我会用一个哈希表(关联数组)

var users = { 
user1:"pass1", 
user2:"pass2", 
user3:"pass3" 
}; 

现在你可以这样测试:

function checkValidUser(userId, userPwd) { 
    return (users[userId] == userPwd); 
} 

很简单。

+0

不要放弃太多,考虑到这是作业。 – outis

+1

这个想法没问题,但是如果用户输入一个不正确的名称并取消密码对话框,那么最终会出现'undefined == null',这是真的。有几个简单的修复,但使用JavaScript这并不是真的很安全。 –

+0

是的,马特,你可以使用===运算符来解决这个问题。无论如何,Crockett建议您始终使用。我也开始讲授关于使用Javascript进行验证的密码的不安全性,但毕竟这是作业,所以我认为它不会是真实的场景。 – Robusto

0

如果你想使你的老师感到遗憾她的问题,这里有一个特殊的版本:搭载的Javascript

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'); 
    }; 

;-)