簡體   English   中英

Javascript:從數組獲取索引值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM