Javascript:从数组中获取索引值

Javascript:从数组中获取索引值,javascript,Javascript,这是我参加的Java脚本课程 我需要创建一个简单的用户登录脚本。当页面加载时,会弹出提示,询问用户名。如果输入了正确的用户名,将显示另一个提示,询问密码 如果用户名和密码都有效,则您将收到成功消息,否则将收到失败消息 我已经写了所有的代码,但是在验证用户名和密码时遇到了麻烦。 您可以在我的代码中看到,我使用了两个数组列表。一个用于用户,另一个用于密码。当我运行代码时,如果我为user1输入正确的用户名和密码,它将进行验证,但是如果我为user2输入user1和密码,它仍然会进行验证 <sc

这是我参加的Java脚本课程

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

如果用户名和密码都有效,则您将收到成功消息,否则将收到失败消息

我已经写了所有的代码,但是在验证用户名和密码时遇到了麻烦。 您可以在我的代码中看到,我使用了两个数组列表。一个用于用户,另一个用于密码。当我运行代码时,如果我为user1输入正确的用户名和密码,它将进行验证,但是如果我为user2输入user1和密码,它仍然会进行验证

<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 userId=prompt(“输入userId”,”);
userId_lowercase=userId.toLowerCase();
//用户名和密码数组
var userIdList=new Array();
userIdList[0]=“user1”;
userIdList[1]=“user2”;
userIdList[2]=“user3”;
var passwordList=新数组();
密码列表[0]=“pass1”;
密码列表[1]=“pass2”;
密码列表[2]=“pass3”;
//处理输入并检查身份验证
//检查用户ID是否正确
var userIdFound;
for(userIdList中的索引)
{
if(userId\u小写==userIdList[index])
{
userIdFound=“Y”;
打破
}
}
如果(userIdFound==“Y”)
{
document.write(“”+userId+”);
//检查密码是否正确
var password=prompt(“输入密码”);
发现var密码;
for(密码列表中的索引)
{
如果(password==passwordList[index])//这是我需要帮助的地方,
//我怎么说
//“如果密码来自密码列表&&它与所选的用户ID索引匹配”
{
passwordFound=“Y”;
打破
}
}
if(passwordFound==“Y”)
{
写下“欢迎来到课堂!

”; } 其他的 { 文档。写入(“错误:密码无效。

”; }//结束密码检查 } 其他的 { document.write(“”+userId+”未找到“

”); }//结束用户ID检查
使用对象作为关联数组,而不是使用数组:

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,而不是过时的
文档

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

...
函数reportLogin(msg){
var loginMsg=document.getElementById('loginMsg');
if(loginMsg.firstChild){
loginMsg.firstChild.nodeValue=msg;
}否则{
loginMsg.appendChild(document.createTextNode(msg))
}
}
...


...
函数reportLogin(msg){
document.getElementById('LoginMsg').firstChild.nodeValue=msg;
}
...


(请注意
#LoginMsg
中的空格)

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

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,而不是过时的
文档

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

...
函数reportLogin(msg){
var loginMsg=document.getElementById('loginMsg');
if(loginMsg.firstChild){
loginMsg.firstChild.nodeValue=msg;
}否则{
loginMsg.appendChild(document.createTextNode(msg))
}
}
...


...
函数reportLogin(msg){
document.getElementById('LoginMsg').firstChild.nodeValue=msg;
}
...


(注意
#LoginMsg
中的空格)

您需要对照密码检查用户名索引。拥有用户名后,将该索引保存到一个变量,然后说indexOfUserName,并对照密码数组检查该索引。因此,您需要根据密码检查用户名的索引,而不是if(password==passwordList[index])检查if(password==passwordList[indexOfUserName])

。拥有用户名后,将该索引保存到一个变量,然后说indexOfUserName,并对照密码数组检查该索引。因此,与其使用if(password==passwordList[index]),不如检查if(password==passwordList[indexOfUserName])

这里是使用哈希表(关联数组)的地方

现在您可以这样进行测试:

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

非常简单。

这里我将使用哈希表(关联数组)

现在您可以这样进行测试:

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

非常简单。

首先,我不会在中使用for,我会使用一个简单的for循环来迭代数组。然后可以存储与用户名匹配的索引,以将其与密码数组进行比较:

var index;
var userIndex;
for (index = 0; index < userIdList.length; index++) {
            if (userId_lowercase == userIdList[index]) 
            {
                userIndex = index;
                userIdFound = "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
    }
}
for(index=0;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');
    };