我正在尝试实现信用卡号的简单验证。我读到了 Luhn 算法 on Wikipedia :
- Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
- Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together with the undoubled digits from the original number.
- If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
在维基百科上,Luhn 算法的描述非常容易理解。但是,我也看到了 Luhn 算法的其他实现 on Rosetta Code和 elsewhere (存档)。
这些实现工作得很好,但我很困惑为什么他们可以使用数组来完成这项工作。他们使用的数组似乎与Luhn算法无关,我看不出他们是如何实现维基百科上描述的步骤的。
他们为什么使用数组?它们的意义是什么,它们如何用于实现维基百科描述的算法?
最佳答案
不幸的是,上面的代码都不适合我。但我在 GitHub 上找到了一个可行的解决方案
// takes the form field value and returns true on valid number
function valid_credit_card(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
// The Luhn Algorithm. It's so pretty.
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
关于javascript - Luhn算法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12310837/