JavaScript - 將巢狀在陣列中的字串內的數字相加
假設我們有一個數組包含一些信用卡演示號碼,如下所示 -
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP