javascript - Luhn算法的实现

标签 javascript algorithm luhn

我正在尝试实现信用卡号的简单验证。我读到了 Luhn 算法 on Wikipedia :

  1. Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
  2. 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.
  3. 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 Codeelsewhere (存档)。

这些实现工作得很好,但我很困惑为什么他们可以使用数组来完成这项工作。他们使用的数组似乎与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/

相关文章:

在可能包含任意数量的重复的列表中查找重复数字的算法

javascript - 如何计算字符串中的某些字符

c++ - 我应该如何处理信用卡号验证算法?

javascript - 可调整大小的 HTML 元素

algorithm - 快速二维模式匹配

javascript - jQuery:每个循环暂停直到完成

algorithm - 平行曲线类图算法

algorithm - 使用 python 检查有效的信用卡号

javascript - 如何使用javascript将变量正确存储到窗口?

javascript - 为什么我的 form.action 与表单提交的不同?