SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Arrays and loops

    Hiya,

    Okay I'm a total beginner in javascript but wanting to learn. I'm working on a very simple website to start myself off, but I'm totally stuck!!
    I have 2 arrays and need to use either a for or while loop (no idea which, as I said, very new to this) to match them up somehow

    var password = new Array (5);
    password[0] = 'password';
    password[1] = 'bluesky';
    password[2] = 'dr45gr6';
    password[3] = 'onlyme';
    password[4] = 'lothlorien';


    var customercodes = new Array (5);
    customercodes[0] ='lt-17';
    customercodes[1] = 'gw-3';
    customercodes[2] = 'lg-9';
    customercodes[3] = 'il-77';
    customercodes[4] = 'fy-32';

    These are the 2 array and I want to put in a prompt window (I can get that far!!! ) to give instruct user to put in a password. The password should then match up the the customercode (like password 1 is customercode 1) and display that on the screen. If a wrong password is entered, it should keep asking til a right one is entered.

    Does anyone have any tips which loops to use and how I should put it??

  2. #2
    SitePoint Wizard chris_fuel's Avatar
    Join Date
    May 2006
    Location
    Ventura, CA
    Posts
    2,750
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, welcome to the forums!

    With web development, Javascript usage tends to be rather tricky. One thing to take into consideration is that a user is able to alter javascript on the fly to get around certain javascript checks (or turn it off completely). Also, people are able to view the source of your page, and would see the login details needed.

    That said, it's a better idea to use a server side language such as PHP to handle authenticating a user. As far as what to do with incorrect logins, most people say the username/password is wrong, but don't give them hints as to what it is. In fact, I know some sites that will completely deactivate your account if you fail to login more than 3 times.

    As for how to store your usernames and paswords, most people do so in a database. One of the more popular databases to work with is MySQL. When storing a password, people will use some kind of encryption to prevent seeing the password. The theory is this:

    1) User signs up, puts in the password they want to use.
    2) The web server takes that password and encrypts it (generally using a method called MD5)
    3) The encryption method is 1 way. Once you encrypt it, there's no way to decrypt it.
    4) Next time the user comes back, they enter in their password and submit it to a secure location (this is done because web traffic passes through many locations, so someone could potentially swipe your password on the way through).
    5) The server encrypts that password (with md5 for example), and compares it to the database version.

    All in all the one rule of thumb I try to live by is that Javascript should enhance a page, but not replace its functionality.

    It seems you're just jumping in, so let me know if anything I said is confusing and I'll expand upon it some more. However, one piece of advice I'd recommend is to shift your learning direction a bit. I'd go with learning HTML/XHTML, then CSS, then a server side scripting language such as PHP (this is recommended for beginners because the language is a bit forgiving). Once you have these as a base, you'll have a better idea on when to use Javascript.

  3. #3
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your reply. I think I understand most of what you're saying, and I do understand what you're saying about security (the encryption bit is a bit beyond my knowledge still but I'll get there). However this is not an actual website I'm gonna be setting up, it's just an example of how to work with Arrays and loops. I'm so very new to this. I've gotten a few books and am studying websites, but it's hard when I don't quite get the basics yet..

  4. #4
    SitePoint Wizard chris_fuel's Avatar
    Join Date
    May 2006
    Location
    Ventura, CA
    Posts
    2,750
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, here's somewhat of an example of how an array works, and how to loop over it. In general, arrays are often created by asking for a group of elements, such as <li>'s (List Items) in this example.

    In this instance, the javascript is grabbing all the li elements on the page, then displaying their nodeName (A fancy way of saying name of the tag) and their innerHTML, which ends up displaying the text content of the list item.

    Code HTML4Strict:
    <html>
    <head>
    <title>Array Test</title>
    <script>
    function displayItems()
    {
    	var list_items = document.getElementsByTagName('li');
    	for ( var i = 0; i < list_items.length; i++)
    	{
    		var current_item = list_items[i];
    		alert(current_item.nodeName + ' ' + current_item.innerHTML);
    	}
    }
     
    window.onload = displayItems;
    </script>
    </head>
    <body>
    <ul>
    	<li>Testing 1</li>
    	<li>Testing 2</li>
    	<li>Testing 3</li>
     
    </ul>
    </body>
    </html>

    Code:
    	var list_items = document.getElementsByTagName('li');
    So here, var is used to declare a variable called list_items. This list_items variable is assigned the value of document.getElementsByTagName('li'). The function document.getElementsByTagName('li') is what is called a "DOM Function". For now, I think you can just leave it at that. This function gets all elements by tag name of "li". So now that we have that:

    Code:
    for ( var i = 0; i <= list_items.length; i++)
    This is what's known as a for loop. There's not many languages that don't have this feature. So to break this down:

    Code:
    var i = 0
    We need some way to go through the array, so we create this counter variable called "i" and set it to 0. The reason why it's set to 0 is because with arrays, the first value is assigned 0, not 1.

    Code:
    i < list_items.length
    Loops can't go on forever, or they bring the system down. This part tells the loop when to stop. In this case, the loop will run as long as i is less than the length of the array of list items.

    Code:
    i++
    Now each time we loop through the array, we need to do something. In this case we increase the value of i by 1. If we don't, then i will forever remain 0, and the part that tells the loop to stop will never be met, causing an infinite loop.

    Code:
    var current_item = list_items[i];
    Here we declare a variable that points to the list item being looped through. Now, if you're only using the value of the list item once, then you can just use list_items[i] and be done with it. However, since we're using it twice, it's faster to put it in a temporary variable, then use that to access it. Not only that, but current_item is a bit easier to read than list_items[i].

    With list_items[i], this means "Get me the element in the list_items array that is in the position referenced to by the value of i (our counter)".

    Code:
    alert(current_item.nodeName + ' ' + current_item.innerHTML);
    and here we display a dialog with the name of the tag (All will say LI, because we told our earlier function to get all LI tags) and the text inside of the list item.

    Okay, so that's a basic example of arrays. If you find you don't get something, let me know.

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,707
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    This sounds like a homework assignment, but nevertheless, here we go.

    Code javascript:
    // arrays defined here, then...
    // init
    var i = 0,
        codeLen = customercodes.length,
        passed,
        pass;
    // loop
    for (i = 0; i < codeLen, i++) {
        passed = false;
        // check
        pass = prompt(customercodes[i] + ': what is the password?');
        if (pass !== password[i]) {
            // loop around again
            i--;
            continue;
        }
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    With your example, you might be better off with a single array which holds a bunch of "objects" instead of one array for customercodes and one for passwords. By having 2 separate arrays, you will have to go to 2 different places if you add/remove a customercode or password.

    Here's an example that combines the password and customercode into a single 'object', and stores those in the array. Note also that there's no need to call 'new Array()', as you can simply define the array with all its members:

    Code JavaScript:
    var credentials = [
        {password : 'password', customercode : 'lt-17' },
        {password : 'bluesky', customercode : 'gw-3' },
        {password : 'dr45gr6', customercode : 'lg-9' },
        {password : 'onlyme', customercode : 'il-77' },
        {password : 'lothlorien', customercode : 'fy-32' }
    ];
    // Loop through the credentials array
    for (var i = 0; i < credentials.length; i++) {
        alert(credentials[i].customercode + ":" + credentials[i].password);
    }

    Hope that helps.

  7. #7
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I like using objects too, but if each element can be uniquely and safely identified I do it like this:
    Code:
    var customers = {
    	'lt-17': {password : 'password', customercode : 'lt-17' },
    	'gw-3': {password : 'bluesky', customercode : 'gw-3' },
    	'lg-9': {password : 'dr45gr6', customercode : 'lg-9' },
    	'il-77': {password : 'onlyme', customercode : 'il-77' },
    	'fy-32': {password : 'lothlorien', customercode : 'fy-32' }
    };
    
    // get customer password for a specific code
    var thecode = 'il-77';
    alert(customers[thecode].password);
    
    // loop through customers
    for (var custcode in customers) {
      alert(customers[custcode].password);
    }
    That way you don't have to loop through any arrays looking for matches.

    The customercode field is redundant in my example but I left it in anyway.

  8. #8
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks everyone!

    I can assure you it was not a homework assignment, I just made up 2 arrays, as I figured it would be harder without any examples
    Chris, that helped tons, I read all of those codes but generally don't 'get' them, so your explanation is much appreciated!!!
    Thanks everyone for showing me new ways to go about arrays. I hope I can ask again in the future if I get totally lost on something. You guys are the best!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •