我正在尝试在javascript中编写一个函数,用于比较列出的字符串中的信用卡号。该函数应找到具有最大总和的信用卡号,并将该数字作为输入数组中的原始字符串返回。我完全陷入困境,无法通过此“未定义”错误消息。这就是我所拥有的:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++) {
var tempArray = inputArray[a].replace(/\D/g, '');
}
function sumDigits(str) {
sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 16);
}
return sum;
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
} else {
return largest;
}
}
var numberArray = [];
console.log(highest(numberArray));
答案 0 :(得分:0)
您的代码中存在大量基本错误。我将简单地将代码修订版放在这里,而不是将其分解。
var ipa = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
function highest(inputArray) {
var currentHighest = 0;
var largest = 0;
var tempArray = [];
for (var a = 0; a < inputArray.length; a++) {
tempArray.push(inputArray[a].replace(/\D/g, ''));
}
function sumDigits(strA) {
var sum = 0;
for (var i = 0; i < strA.length; i++) {
sum += parseInt(strA.charAt(i), 10);
}
return sum;
}
for (var a = 0; a < tempArray.length; a++) {
var csum = sumDigits(tempArray[a]);
if (csum >= currentHighest) {
currentHighest = csum;
largest = inputArray[a];
}
}
return largest;
}
console.log(highest(ipa));
答案 1 :(得分:-1)
根据我对您的问题的理解,我希望这是您正在寻找的。 p>
除了对数组进行基本循环外,您还可以按升序对数组进行排序,只需挑选出最大信用卡号的数组的最后一项。
示例小提琴:
https://jsfiddle.net/xxo3m8zf/1/
示例功能:
function largestSum(arr) {
arr.sort();
return largest = arr[arr.length-1];
}
答案 2 :(得分:-1)
'use strict';
// initial array of numbers
let numbers = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
// remove "-" symbol
let normilized = numbers.map(number => number.replace(/-/g, ''));
// get sum for each number
let sums = normilized.map(
number => [].reduce.call(number, (prev, value) => {
prev += +value;
return prev;
}, 0));
// find max sum
let max = Math.max.apply(null, sums);
// find position of that sum
let indexOfMax = sums.indexOf(max);
// get card number
console.log(numbers[indexOfMax]);