简体   繁体   中英

Javascript, validation, for-loops

I am writing a validator for credit card numbers in Javascript. I want it to be check against the LUHN-variable and I want to write the steps myself and I try to do this with help of for loops in order to practice them. However, I am stuck and I could use some friendly advice on what to do from here on. I am also slightly troubled with the entire syntax of the for loop, any tips on how to improve them is welcome.

The project is here: http://jsfiddle.net/tomasantonj/eZKMa/12/

Here is the code I am having trouble with:

else if (filter.test(cardnumber.value))
{

  // 1. Begin with second to last number iterate, every second number with 2 until start.
    for(i = 0; i < cardnumber.length;i += 1){
    newnumbers = (i * 2);

  // 2. The result of the previous string to be added i+i+i.
    for (i = 0; i < newnumbers.length; i += 1){   
    sum1 = (i + i);


  // 3. Then add the remaining numbers together but skip the last which is a control number.
    for (i = 0; i < cardnumber.length; i += 1){
    sum2 = (i + i);

  // 4. Add sum1 and sum2 together

    var checksum = (sum1 + sum2);

    alert('the sum of x and y is: ' + checksum);
    // 5. Mod10 out of the checksum + cardnumber control number to get validity.
    if ((checksum + cardnumber[-0]) % 10 === 0){
            alert('LUHN checks out!');
    }
    else {
    alert('not yet');
    }
   }  
  } 
 }

I am unsure how to ask the proper question, but I am guessing my problems are variable scope, the for loops and getting the for loops to do index based queries. I am aware of this code being ugly and long, this is my second ever javascript attempt so please don't mind it too much.

When this code is run, checksum is undefined- anyone know why this is? Something to do with strings and integers maybe? :S

Any response is highly appreciated. Thank you, Tomas

Is it ok that you are using the same variable "i" in all your nested for loops? that doesn't look good to me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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