2012-04-18 44 views
0

我正在爲Javascript中的信用卡號碼編寫驗證程序。我希望它能夠檢查LUHN變量,並且我想自己編寫這些步驟,並且我嘗試在for循環的幫助下做到這一點,以便練習它們。 但是,我卡住了,我可以使用一些友好的建議,在這裏做什麼。 我也對for循環的整個語法有些困惑,所以如何改進它們的提示是值得歡迎的。Javascript,驗證,for-loops

該項目是在這裏: http://jsfiddle.net/tomasantonj/eZKMa/12/

這裏是我遇到的麻煩的代碼:

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'); 
    } 
    } 
    } 
} 

我不確定如何提出正確的問題,但我猜我的問題是變量範圍,for循環和獲取for循環來執行基於索引的查詢。我知道這段代碼很醜,很長,這是我第二次嘗試JavaScript,所以請不要太在意。

運行此代碼時,校驗和未定義 - 任何人都知道這是爲什麼?可能與字符串和整數有關? :S

任何迴應非常感謝。 謝謝, Tomas

+0

如果你可以使用jQuery有一個優秀的信用卡驗證插件,檢查盧恩校驗和以及確定卡的類型:https://github.com/PawelDecowski/jQuery-CreditCardValidator – 2012-04-18 11:14:03

+0

啊,我不能,這是我得到一個學校項目的任務,它應該是JavaScript。沒有圖書館等,但謝謝! – tomasantonj 2012-04-18 11:16:07

回答

1

你可以在所有的嵌套for循環中使用相同的變量「我」嗎?那對我來說並不好看!

+0

最有可能非常真實!我剛剛嘗試了一些重構循環,循環首先不是嵌套的,並且使用了相同的變量「我」 - 這可以嗎? – tomasantonj 2012-04-18 11:10:53

+0

如果循環沒有嵌套,重用這個變量就沒有問題,但是在嵌套循環中你不應該這樣做,除非你想要的是相同的東西(你想跳過或重複一些更高層次的循環) – gabitzish 2012-04-18 11:12:58