简体   繁体   English

Javascript:从数组获取索引值

[英]Javascript: Get the Index Value from an Array

This is for a Java script course that Im taking... 这是我正在学习的Java脚本课程...

I need to create a simple user-login script. 我需要创建一个简单的用户登录脚本。 When the page loads a prompt pops up asking for the user name. 页面加载后,会弹出提示询问用户名。 If the correct username is entered, another prompt is displayed asking for a password. 如果输入正确的用户名,则会显示另一个提示,要求输入密码。

If both the username and valid, then you a sucessful message, otherwise you get a failure message. 如果用户名和用户名均有效,那么您将收到一条成功消息,否则您将收到一条失败消息。

I've written all of the code, but am having trouble with validating the username and password. 我已经编写了所有代码,但是在验证用户名和密码时遇到了麻烦。 You can see in my code that I'm using two array lists. 您可以在我的代码中看到我正在使用两个数组列表。 One for users and another for passwords. 一个用于用户,另一个用于密码。 When I run my code, if I type in the correct username and password for user1, it validates, BUT if I enter user1 and the password for user2, it still validates. 当我运行代码时,如果我输入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>

Rather than using arrays, use objects as associative arrays: 而不是使用数组,而是将对象用作关联数组:

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

It's a good thing this is homework, otherwise I'd have to smack you with a board of cluefulness due to the inherent insecurity. 这是一项家庭作业,这是一件好事,否则由于内在的不安全感,我不得不给您一个笨拙的提示。

You should also look into using the DOM API rather than the antiquated document.write . 您还应该研究使用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>

or 要么

<script type="text/javascript">
  ...
  function reportLogin(msg) {
    document.getElementById('LoginMsg').firstChild.nodeValue=msg;
  }
</script>
...
<p id="LoginMsg"> </p>

(Note the space in #LoginMsg .) (请注意#LoginMsg的空格。)

First of all, I wouldn't use for-in, I'd use a simple for loop to iterate over the array. 首先,我不会使用for-in,而是使用简单的for循环遍历数组。 Then you could store the index that matches the user name to compare it to the password array: 然后,您可以存储与用户名匹配的索引,以将其与密码数组进行比较:

var index;
var userIndex;
for (index = 0; index < userIdList.length; index++) {
            if (userId_lowercase == userIdList[index]) 
            {
                userIndex = index;
                userIdFound = "Y";
                break;
            }
}

Then, in your password loop you'd say: 然后,在密码循环中,您会说:

if (password == passwordList[index] && index == userIndex)
{
    passwordFound = "Y";
    break;
}

That's the simple way around the problem. 这是解决问题的简单方法。 I don't know how much you've learned but you could also use an array of objects: 我不知道您学到了多少,但您也可以使用一系列对象:

var userLogins = [{user:"user1", password:"pass1"},...etc];

And then loop through that array once after asking for the name and password and seeing if they match: 然后在询问名称和密码并查看它们是否匹配后循环遍历该数组:

for (index = 0; index < userLogins.length; index++) {
    if (userLogins.user == userId_lowercase && userLogins.password == password) {
        //Do stuff here
    }
}

The thing to keep in mind is that you have to link the user name to the password somehow. 要记住的是,您必须以某种方式将用户名链接到密码。 The way you're currently doing this is by the index in both arrays, but that isn't guaranteed. 您当前执行此操作的方式取决于两个数组中的索引,但这不能保证。 It'd be much better to link the two bits of information in some way, as in the array of objects above. 最好以某种方式链接这两部分信息,例如上面的对象数组。

Here is where I would use a hash table (associative array) 这是我将使用哈希表(关联数组)的地方

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

Now you can test like this: 现在您可以像这样测试:

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

Very simple. 很简单。

You will need to check the index of the username against the password. 您将需要对照密码检查用户名的索引。 Once you have the username save that index to a variable say indexOfUserName and check that index against your password array. 一旦有了用户名,就将该索引保存到变量中,说indexOfUserName并对照密码数组检查该索引。 So instead of if (password == passwordList[index]) check if (password == passwordList[indexOfUserName]) 因此,请检查(Password == passwordList [indexOfUserName])是否是if(password == passwordList [index])

If you want to make your teacher regrets her question, here's a special version: 如果您想让老师后悔她的问题,请使用以下特殊版本:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM