我正在尝试使用JavaScript创建一个CS50卡验证器。我在校验和计数方面遇到问题。应该是sum % 10 === 0 //true
。
let cards = [378282246310005, 371449635398431,
5555555555554444, 5105105105105100, 4012888888881881,
4012888888881880, 1234567890, 361049635398431], result = '';
cards.forEach( card => {
if (isCardValid(card)) {
result += card + ' = ';
checkBank(card);
}
});
document.getElementById('task6').innerHTML = result;
function checkBank(card) {
if ((card >= 340000000000000 && card < 350000000000000) || (card >= 370000000000000 && card < 380000000000000))
result += ("AMEX\n");
else if (card >= 5100000000000000 && card < 5600000000000000)
result += ("MASTERCARD\n");
else if ((card >= 4000000000000 && card < 5000000000000) || (card >= 4000000000000000 && card < 5000000000000000))
result += ("VISA\n");
else
result += ("INVALID\n");
}
function isCardValid(digits) {
let sum = 0;
for (let i = 0; i < digits.length; i++) {
let cardNum = parseInt(digits[i]);
if ((digits.length - i) % 2 === 0) {
cardNum = cardNum * 2;
if (cardNum > 9) {
cardNum = cardNum - 9;
}
}
sum += cardNum;
}
return sum % 10 === 0;
}
以下是一些用于验证验证器工作的数据:
//AMEX
//AMEX
//MASTERCARD
//MASTERCARD
//VISA
//INVALID
//INVALID
//INVALID
最主要的是,我不能使用字符串,数组和任何准备使用的函数。等待您的帮助,谢谢。
UPD 我用除这张卡以外的算法解决了这个问题:
//INVALID
我的代码认为这是一张VISA卡。银行验证看起来不错,所以我不知道在哪里找到问题。有什么建议吗?
UPD2 最终版本
let cards = [378282246310005, 371449635398431,
5555555555554444, 5105105105105100, 4012888888881881,
4012888888881880, 1234567890, 361049635398431], result = '';
cards.forEach( card => {
if (isCardValid(card)) {
result += card + ' = ';
checkBank(card);
} else {
result += card + ' = INVALID Card\n'
}
});
document.getElementById('task6').innerHTML = result;
function checkBank(card) {
if ((card >= 340000000000000 && card < 350000000000000) || (card >= 370000000000000 && card < 380000000000000))
result += ("AMEX\n");
else if (card >= 5100000000000000 && card < 5600000000000000)
result += ("MASTERCARD\n");
else if ((card >= 4000000000000 && card < 5000000000000) || (card >= 4000000000000000 && card < 5000000000000000))
result += ("VISA\n");
else
result += ("INVALID Bank\n");
}
function isCardValid(card) {
let sum = 0, len, first = 0, second = 0;
for (len=0; card; Math.floor(card /= 10), ++len) {
let digit = Math.floor(card % 10);
second = first;
first = digit;
if (len & 1) {
digit += digit;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
}
return sum % 10 === 0;
}
<pre id="task6"></pre>