在 if / else 语句中获取"无法读取未定义的属性'计数'"(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声明变量时,它的作用域为块。在您的情况下,count不存在于if(…) {…} 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

最新更新