const batch = [valid1, valid2, valid3, valid4, valid5, invalid1, invalid2, invalid3, invalid4, invalid5, mystery1, mystery2, mystery3, mystery4, mystery5]
// Add your functions below:
function validateCred(array) {
let sumArray= []
for (i=0; i < array.length ; i++){
//console.log(i)
if (array.length%2 !==0 ) {
if(i%2 !==0) {
if(array[i]*2 < 10){
sumArray.push(array[i]*2)
} else{
sumArray.push(array[i]*2-9)
}
} else {
sumArray.push(parseInt(array[i],10))
}
} else { if(i%2 ===0) {
if(array[i]*2 < 10){
sumArray.push(array[i]*2)
} else{
sumArray.push(array[i]*2-9)
}
} else {
sumArray.push(parseInt(array[i],10))
}
}
}
if(sumArray.reduce( (prv, cur) => prv + cur) % 10===0) {
return true
}else{
return false
}
}
function findInvalidCards(nestedArray) {
let nestedArrayInvalid= [] ;
for(i=0; i < nestedArray.length; i++){
if(validateCred(nestedArray[i]) === false){
nestedArrayInvalid.push(nestedArray[i])
}
}
return nestedArrayInvalid
}
console.log(findInvalidCards(batch))
我正在编写一个信用卡检查器,luhn algorithim函数已完成,但是现在我正尝试获取一个嵌套数组,并将所有无效的卡添加到数组中,如第二个函数所示,但这似乎并没有工作,我不知道怎么了
答案 0 :(得分:1)
我不确定您的validateCred()
函数如何返回数据,但是当它逐个元素地返回true或false时,findInvalidCards()
似乎可以正常工作:
const batch = [true, false, false, true, true]
// Add your functions below:
function validateCred(arrayItem) {
return arrayItem
}
function findInvalidCards(nestedArray) {
let nestedArrayInvalid= [];
for(i=0; i < nestedArray.length; i++){
if(validateCred(nestedArray[i]) === false){
nestedArrayInvalid.push(nestedArray[i])
}
}
return nestedArrayInvalid
}
console.log(findInvalidCards(batch))