我正在尝试使用Luhn的算法创建一个简单的信用卡验证器。如果校验数字与最后输入的数字匹配,那么它应该提醒用户它是有效的。否则,说它无效。目前,我得到了一个错误,我的总和作为NaN。我想这是代码的唯一问题。
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "212121212121212";
let multipliedNumber;
let multipliedString;
if (number.length != 16) {
alert("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length - 1; count++) {
multipliedNumber = number[count] * multiplier[count];
console.log(multipliedNumber);
if (multipliedNumber > 9) {
multipliedNumber = multipliedNumber[0] + multipliedNumber[1];
multipliedString = multipliedString + multipliedNumber;
} else {
multipliedString = multipliedString + multipliedNumber;
}
}
console.log(multipliedString);
let checkDigit = 10 - (multipliedString % 10);
if (checkDigit == number[15]) {
alert(`${number} is a valid Credit Card number.`);
} else {
alert(`${number} is not a valid Credit Card number.`);
}
}
}
有几个问题:
-
multipliedNumber
为产品,为数字类型。因此,在它上面访问[0]
或[1]
的属性,只会求值为undefined
。要么先将该值转换为string,要么(更好)使用算术方法提取两个数字:multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
-
multipliedString
未初始化,因此向其添加内容将不会给出期望的结果。其次,您将其定义为字符串,但它应该是一个数字,因为在Luhn的算法中,您应该将结果数字相加,而不是将它们连接起来。那么像这样初始化一个变量:sum = 0;
…并像以前那样使用它——尽管您可以从
+=
操作符中获益,并且由于这两种情况的操作是相同的,因此您可以在if..else
块之外进行操作。 -
当模运算结果为0时,校验位的计算错误:
10 - (multipliedString % 10)
然后返回10,但在这种情况下,校验位应该是0。在循环中处理最后一位数字,然后检查是否得到了10的倍数,这要简单得多。这也是该算法在维基百科上的解释
修正版:
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "2121212121212121"; // One more character added...
let multipliedNumber;
let sum = 0 // Initialise it as a number.
if (number.length != 16) {
console.log("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length; count++) { // Include last digit in loop
multipliedNumber = number[count] * multiplier[count];
if (multipliedNumber > 9) {
// Use arithmetic to add the two digits
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
}
sum += multipliedNumber;
}
let check = sum % 10; // Simpler now because all digits were processed
if (check == 0) { // Sum is multiple of 10
console.log(`${number} is a valid Credit Card number.`);
} else {
console.log(`${number} is not a valid Credit Card number.`);
}
}
}
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">