在 if / else 语句 (Javascript) 中获取“无法读取未定义的 属性 'count'”

getting 'Cannot read property 'count' of undefined' in an if / else statement (Javascript)

我有一个数组约会对象,每个对象都有这个键:"RecurrenceRule"。它要么为空 (null),要么具有以下内容:"RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;"

这是一个元素的样子:

{ appointmentId: 001239,
    subject: "Something",
    Client: "Bob",
    StartTime: "2020-04-16T11:00:00.000Z",
    EndTime: "2020-04-16T11:30:00.000Z",
    km: 90,
    RecurrenceRule: null,
},

我想做的是通过 .reduce() 函数遍历 appointments,如果当前元素有 "RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;",我想取 'COUNT=' 之后的值,并且将它分配给 count,如果 RecurrenceRulenull,我想将 1 分配给 count,如果这有意义的话。下面是方法:

 export class AppointmentComponent implements OnInit {
appointments;


ngOnInit(){
this.getAppointments();
}


  getAppointments(){
this.appointmentService.getAppointments().subscribe((data : any) => {
  this.appointments= data.appointment;
  this.groupByClient();

});
 };

  groupByClient(){
  var result = [];

  this.appointments.reduce(function (res, value) {
    let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "hour",true) % 60;
    if(res[value.RecurrenceRule] !== null) {
      let count =  parseInt(value.RecurrenceRule.split("COUNT=")[1])
    } else {
      let count =  1;
    }
    if (!res[value.Client]) {

      res[value.Client] = {
        km: value.km,
        Client: value.Client,
        count: this.count,
        difference: diff * this.count     
      };
      result.push(res[value.Client]);

    } else {
      res[value.Client].km += value.km;
      res[value.Client].difference += diff;
    }

    return res;
  }, {});
}
}

但是,当我 运行 这样做时,我收到错误消息:ERROR TypeError: Cannot read property 'count' of undefined,指向 this.count 行。这里出了什么问题?与嵌套 this. 有关吗?

如果您需要更多信息,请告诉我。

当您使用 let 声明一个变量时,它的作用域是块。在你的情况下 countif(…) {…} else {…}

之外不存在

你应该写

let count;
if(value.RecurrenceRule !== null) {
      count =  parseInt(value.RecurrenceRule.split("COUNT=")[1])
    } else {
      count =  1;
    }

const count = value.RecurrenceRule ? parseInt(value.RecurrenceRule.split("COUNT=")[1]) : 1;

稍后在您的代码中使用 count 而不是 this.count