我有一個來自日期選擇器的 fromDate 和 toDate - 假設 fromDate 是 2021 年 9 月 5 日,而 toDate 是 2022 年 2 月 2 日,我需要兩者之間缺失月份的串列。我最初嘗試使用 moment.js 并使用 arr.reduce 和 arr.findIndex 函式。但沒有得到預期的輸出。請幫忙。
例如。
var arr = [
{month: 7, year: 2021, count: 21},
{month: 12, year: 2021, count: 54},
{month: 2, year: 2022, count: 76}
];
預期 o/p =
[
{month: 7, year: 2021, count: 21},
{month: 8, year: 2021, count: 0},
{month: 9, year: 2021, count: 0},
{month: 10, year: 2021, count: 0},
{month: 11, year: 2021, count: 0},
{month: 12, year: 2021, count: 54},
{month: 1, year: 2022, count: 0},
{month: 2, year: 2022, count: 76}
];
uj5u.com熱心網友回復:
一種方法是將年份和月份視為一個值。例如。 var ym = year * 12 month
如果你這樣做,那么你可以將 YM 值與陣列中的下一個專案進行比較,如果它在下面,那么你可以在它們之間的陣列中插入一個新專案。
下面是一個例子..
var arr = [
{month: 7, year: 2021, count: 21},
{month: 12, year: 2021, count: 54},
{month: 2, year: 2022, count: 76}
];
function fillSpace(arr) {
let st = 0;
while (st < arr.length -1){
const thisItem = arr[st];
const nextItem = arr[st 1];
const thisYM =
thisItem.year * 12 thisItem.month;
const nextYM =
nextItem.year * 12 nextItem.month;
if (thisYM 1 < nextYM) {
arr.splice(st 1, 0, {
month: (thisYM 1) % 12,
year: Math.trunc((thisYM 1) / 12),
count: 0
});
}
st = 1;
}
}
fillSpace(arr);
console.log(arr);
uj5u.com熱心網友回復:
看看這個 - 我將月份添加到年份以獲得月差
let arr = [{ month: 7, year: 2021, count: 21 }, { month: 12, year: 2021, count: 54 }, { month: 2, year: 2022, count: 76 }];
const newArr = arr.reduce((acc, cur, i) => {
const found = acc.length > 0 && acc.findIndex(item => item.month === cur.month && item.year === cur.year) != -1
if (!found) acc.push(cur)
const next = i < arr.length - 1 ? arr[i 1] : cur; // if the same the diff is 0
const nextMonths = (next.year*12) next.month
const curMonths = (cur.year*12) cur.month
const diff = nextMonths - curMonths;
let d = new Date(cur.year,cur.month-1,1,15,0,0,0);
for (let i=0; i<diff; i ) {
d.setMonth(d.getMonth() 1)
acc.push({
year: d.getFullYear(),
month: d.getMonth() 1,
count: 0
})
}
return acc
}, [])
console.log(newArr)
uj5u.com熱心網友回復:
新日期(新日期(d2)-新日期(d1)).getMonth();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/424387.html
標籤:javascript 数组 有角度的 打字稿 约会时间
上一篇:為什么我的矩陣顯示錯誤的輸出?
