我正在爲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
如果你可以使用jQuery有一個優秀的信用卡驗證插件,檢查盧恩校驗和以及確定卡的類型:https://github.com/PawelDecowski/jQuery-CreditCardValidator – 2012-04-18 11:14:03
啊,我不能,這是我得到一個學校項目的任務,它應該是JavaScript。沒有圖書館等,但謝謝! – tomasantonj 2012-04-18 11:16:07