我很少有這樣的清單
a = [ 2, 47-54, 68-69, 120-121, 318, 320, 342, 364-366, 414-422, 503-505, 513-514, 529, 554, 586, 690, 775, 913, 1018, 1117, 1159, 1183, 1218-1219, 1379, 1478, 1491, 1497, 1510, 1562, 1601, 1664, 1673, 1686, 1692, 1710, 1759-1765, 1862-1881, 1951-1962, 1992, 2020 ]
b = [ 18, 28, 34-35, 58-84, 110-137, 139-191, 193-272 ]
value of b = 192
嘗試獲取一個簡單的 javascript 代碼來獲取不同范圍之間的值的總數,并添加單個數字,正如我對 b 的值所提到的。
uj5u.com熱心網友回復:
你可以做這樣的事情
const b = [ '18', '28', '34-35', '58-84', '110-137', '139-191', '193-272' ]
const calculateTotalNumbers = data => data.reduce((res, n) => {
const [n1, n2] = n.split('-').map(Number)
if(n2){
return res n2 - n1 1
}
return res 1
}, 0)
console.log(calculateTotalNumbers(b))
uj5u.com熱心網友回復:
您可以使用Array.prototype.reduce來完成。
const
lines = ["18", "28", "34-35", "58-84", "110-137", "139-191", "193-272"],
result = lines.reduce((r, line) => {
const [start, stop = start] = line.split("-").map(Number);
return r stop - start 1;
}, 0);
console.log(result);
注意:要處理單行,我默認stop為start.
uj5u.com熱心網友回復:
您可以使用 迭代陣列中的reduce值,在 a 上拆分值-并將結果添加1(當沒有時-)或結束值和開始值之間的差異(包含范圍為 1):
const b = ['18', '28', '34-35', '58-84', '110-137', '139-191', '193-272']
const numsInc = (arr) => arr.reduce((acc, v) => {
[s, e] = v.split('-');
acc = e ? parseInt(e,10)-parseInt(s,10) 1 : 1
return acc;
}, 0)
const numsExc = (arr) => arr.reduce((acc, v) => {
[s, e] = v.split('-');
acc = e ? parseInt(e,10)-parseInt(s,10) : 1
return acc;
}, 0)
console.log(numsInc(b))
console.log(numsExc(b))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492378.html
標籤:javascript
上一篇:如何使用過濾方法獲取陣列資料?
