【发布时间】:2020-04-21 20:41:53
【问题描述】:
我有一个数组约会对象,每个对象都有这个键:"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 和如果RecurrenceRule 是null,我想将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. 有关吗?
如果您需要更多信息,请告诉我。
【问题讨论】:
-
您显示的所有代码在哪里?如果有更大的功能呢?您已经使用
this.appointments.reduce启动了reduce调用,因此除非您展示如何调用该代码,否则我们无法知道this是什么。 -
这个函数在 ngOnInit() 函数中被调用,如果你是这个意思?
-
我不知道这是否是我们需要的。请编辑您的问题并显示包含您显示的代码的完整方法。但是,根据你在这里所说的,
this没有引用你的对象数组,因此你的错误。如果从ngOnInit()调用该方法,则this可能是window。您可以通过在reduce调用之前添加console.log(this)来找出this指向的内容。 -
如果您已将数组声明为
appointments,您也可以从this.appointments.reduce中删除this并使其成为appointments.reduct(res, value, arr),然后将this.count替换为arr.count -
我已经更新了我的问题,以提供更多关于何时调用函数的上下文。
console.log(this)之前的this.appointments.reduce指向整个组件
标签: javascript arrays properties this undefined