JavaScript - 对嵌套在数组中的字符串中的数字求和
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 15:08:17
假设我们有一个数组,其中包含一些像这样的演示信用卡号 −
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
我们的任务是创建一个接受此数组的函数。该函数必须返回数字总和最大的信用卡号。
如果两个信用卡号的数字总和相同,则该函数应返回最后一个信用卡号。
示例
其代码为 −
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
const findGreatestNumber = (arr) => {
let n, i = 0, sums;
sums = [];
while (i < arr.length) {
sums.push(sum(arr[i]));
i++;
}
n = sums.lastIndexOf(Math.max.apply(null, sums));
return arr[n];
}
const sum = (num) => {
let i, integers, res;
integers = num.split(/[-]+/g);
i = 0;
res = 0;
while (i < integers.length) {
res += Number(integers[i]);
i++;
}
return res;
};
console.log(findGreatestNumber(arr));
输出
控制台中的输出将是 −
4252-278893-7978
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

