与函数一起使用时的数组问题



我试图使用我的validateCred()函数,它可以检查信用卡数组并返回有效或无效并且工作正常。还有一个批处理数组,其中包含所有数组。问题是,在我的findInvlaidCards()函数中,当我想在if语句中使用validateCred()方法时,我在findInvalidCards()函数的for循环中循环批处理数组,它将数组转换为不同的数组。检查findInvalidCred()内部的if语句,我添加了一条注释,也得到了输出。请帮忙并尽你所能解释清楚。

// All invalid credit card numbers
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
const invalid2 = [5, 7, 9, 5, 5, 9, 3, 3, 9, 2, 1, 3, 4, 6, 4, 3];
const invalid3 = [3, 7, 5, 7, 9, 6, 0, 8, 4, 4, 5, 9, 9, 1, 4];
const invalid4 = [6, 0, 1, 1, 1, 2, 7, 9, 6, 1, 7, 7, 7, 9, 3, 5];
const invalid5 = [5, 3, 8, 2, 0, 1, 9, 7, 7, 2, 8, 8, 3, 8, 5, 4];
const invalid6 = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6];
// Can be either valid or invalid
const mystery1 = [3, 4, 4, 8, 0, 1, 9, 6, 8, 3, 0, 5, 4, 1, 4];
const mystery2 = [5, 4, 6, 6, 1, 0, 0, 8, 6, 1, 6, 2, 0, 2, 3, 9];
const mystery3 = [6, 0, 1, 1, 3, 7, 7, 0, 2, 0, 9, 6, 2, 6, 5, 6, 2, 0, 3];
const mystery4 = [4, 9, 2, 9, 8, 7, 7, 1, 6, 9, 2, 1, 7, 0, 9, 3];
const mystery5 = [4, 9, 1, 3, 5, 4, 0, 4, 6, 3, 0, 7, 2, 5, 2, 3];
// An array of all the arrays above
const batch = [valid1, valid2, valid3, valid4, invalid1, invalid2, invalid3, invalid4,
invalid5, invalid6, mystery1, mystery2, mystery3, mystery4, mystery5];

// Add your functions below:
function validateCred(arr){
let sum = 0;
for (let i = arr.length - 1; i >= 0; i--) {
if(i % 2 == 0){
arr[i] *= 2;
if(arr[i] > 9){
arr[i] -= 9;
}
sum += arr[i];
} else {
sum += arr[i];
}
}
if (sum % 10 == 0){
return "Invalid";
} else {
return "Valid";
}
}
function findInvalidCards(array){
const invalidArrays = [];
for(let i = 0; i < array.length; i++){
//console.log(array[i]);
if(validateCred(array[i]) == "Invalid"){
console.log(array[i]);
/* this if statment returns these arrays which are not what i have
[ 8, 5, 6, 9, 3, 7, 5, 9, 0, 8, 0, 1, 3, 8, 0, 8 ]
[ 1, 5, 6, 5, 5, 6, 3, 7, 3, 8, 5, 5, 2, 4, 6, 9 ]
[ 3, 0, 2, 1, 2, 4, 8, 3, 8, 0, 3, 8, 4, 9, 0, 5 ]
[ 8, 5, 6, 9, 8, 0, 8, 9, 3, 7, 7, 6, 9, 6, 3, 6 ]
[ 1, 4, 3, 6, 2, 0, 0, 8, 3, 1, 3, 2, 0, 2, 6, 9 ]
[ 3, 0, 2, 1, 6, 7, 5, 0, 4, 0, 9, 6, 4, 6, 1, 6, 4, 0, 6 ]
[ 8, 9, 2, 3, 1, 4, 0, 4, 3, 3, 0, 7, 4, 5, 4, 3 ]*/
invalidArrays.push(array[i]);
}
}
//console.log(invalidArrays)
return invalidArrays;
}
findInvalidCards(batch);

您正在更改validateCred函数中的原始数组。您可以将数组元素的值存储在一个变量中,然后对其进行任何您想要的操作。

function validateCred(arr) {
let sum = 0
let currentNumber
for (let i = arr.length - 1; i >= 0; i--) {
currentNumber = arr[i]
if (i % 2 == 0) {
currentNumber *= 2
if (currentNumber > 9) {
currentNumber -= 9
}
}
sum += currentNumber
}
if (sum % 10 == 0) {
return 'Invalid'
} else {
return 'Valid'
}
}

相关内容

  • 没有找到相关文章

最新更新