我想解釋一下為什么這個 else if 陳述句的結果與我的期望不符。我的 if 陳述句作業正常,但 else if 陳述句將相同的值推送到我的陣列。我想要做的是,如果在此期間結束時人大于 18 歲,我希望 childEndDate 是他/她將成為 18 歲的人的日期。
這是我的堆疊閃電戰
this.childbirthYear.forEach(element => {
if (periodEndYear - element < 18) {
this.childEndDate = this.endDate;
} else if (periodEndYear - element >= 18) {
this.childBirthDate.forEach(year => {
this.childEndDate = addYears(new Date(year), 18).toISOString();
});
}
this.final.push(this.childEndDate);
});
console.log(this.final)
我現在的人日期是:
this.childBirthDate = [
'2012-02-16T20:00:00.000Z',
'2010-05-19T20:00:00.000Z',
];
陣列回傳
[“2028-05-19T20:00:00.000Z”、“2028-05-19T20:00:00.000Z”]
但它必須回傳
[“2030-05-19T20:00:00.000Z”、“2028-05-19T20:00:00.000Z”]
uj5u.com熱心網友回復:
如果你想this.childEndDate保留這個人成為 18 歲的年份,只需將element保留出生年份的年份加上 18
不知道你為什么在 else if 中使用另一個 forEach 回圈
this.childbirthYear.forEach(element => {
if (periodEndYear - element < 18) {
this.childEndDate = this.endDate;
} else if (periodEndYear - element >= 18) {
this.childEndDate = addYears(new Date(element), 18).toISOString();
}
this.final.push(this.childEndDate);
});
console.log(this.final)
給出輸出
['2030-01-01T00:00:00.000Z', '2028-01-01T00:00:00.000Z']
uj5u.com熱心網友回復:
我認為以下代碼應該為您做...
const lessThan18s = this.childBirthDate.filter(birthDate => (periodEndYear - new Date(birthDate).getFullYear()) < 18);
const greaterThan18s = this.childBirthDate
.filter((birthDate: string) => (periodEndYear - new Date(birthDate).getFullYear()) >= 18)
.forEach((birthDate: string) => {
this.final.push(addYears(new Date(birthDate), 18).toISOString());
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349972.html
標籤:javascript 打字稿
