-1
我想驗證基於Luhn公式的JavaScript的信用卡號碼。我意識到有這個插件,但是想自己試試。我已經包含了一個應該是有效的test credit card number。不幸的是,我收到了無效的結果。所以,我猜我在邏輯上犯了一個錯誤。我正在尋找一些幫助,看看我可能出錯的地方。CC驗證(LuhnFormula)錯誤
var ccNumber = "5185763365093706";
var finalArray = [];
var lastNumber;
function validateCC() {
// convert CCNumber to array
var ccArray = ccNumber.split("");
// Remove the last number from the array, and store it as a number in a variable
lastNumber = ccArray.pop() * 1;
var ccReverse = Array.prototype.slice.call(ccArray).reverse();
for(var i = 0; i < ccReverse.length; i++) {
var newNumber;
// for all the odd numbers in the
if(i %2 === 0) {
// multiply each odd numbered array item by 2
var newCalc = ccReverse[i] * 2;
var finalCalc;
// check to see if the resulting calculation is greater than 9
(function() {
if(newCalc > 9) {
finalCalc = newCalc - 9;
} else {
finalCalc = newCalc;
}
})();
// push each odd number to the finalArray
finalArray.push(finalCalc);
}
}
}
validateCC();
// Add up all the numbers in the final array
var total = (finalArray.reduce(addArray, 0));
function addArray(a, b) {
return a + b;
}
// The number above should be valid, but it's returning false.
if(total % 10 === lastNumber) {
console.log("Is a valid credit card");
} else {
console.log("Is not a valid credit card");
}
我也有很多評論jsbin:任何幫助,非常感謝。
感謝您的反饋意見。我會看一下,看看我可以如何根據你發佈的例子進行改進。 – somecallmejosh