简体   繁体   English

使用嵌套的 forEach 循环推送到数组

[英]Using nested forEach loops to push to an array

I'd love an explanation as to why the result of this else if statement doesn't match my expectation.我想解释一下为什么这个 else if 语句的结果与我的期望不符。 my if statement works fine, but else if statement pushes the same value to my array.我的 if 语句工作正常,但 else if 语句将相同的值推送到我的数组。 what I am trying to do is that, if by end of the period person is greater than 18 i want childEndDate to be dates of person date when he/she will become 18 years old.我想要做的是,如果在此期间结束时人大于 18 岁,我希望 childEndDate 是他/她将成为 18 岁的人的日期。

here is my stackblitz这是我的堆栈闪电战

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)

person dates i have now is:我现在的人日期是:

this.childBirthDate = [
  '2012-02-16T20:00:00.000Z',
  '2010-05-19T20:00:00.000Z',
];

array returns数组返回

["2028-05-19T20:00:00.000Z", "2028-05-19T20:00:00.000Z"] [“2028-05-19T20:00:00.000Z”、“2028-05-19T20:00:00.000Z”]

but it must return但它必须返回

["2030-05-19T20:00:00.000Z", "2028-05-19T20:00:00.000Z"] [“2030-05-19T20:00:00.000Z”、“2028-05-19T20:00:00.000Z”]

If you want this.childEndDate to hold the year when the person became 18 simply take the element which hold the birthyear and add with 18如果您希望this.childEndDate保存人成为 18 岁的年份,只需将保存出生年份的element加上 18

dont know why you are using another forEach loop inside the else if不知道你为什么在 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)

Gives output给出输出

['2030-01-01T00:00:00.000Z', '2028-01-01T00:00:00.000Z']

I think the following code should do for you...我认为以下代码应该为您做...

    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());
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM