我在TypeScript中实现了以下代码。
class Task {
text: string
userId: string
constructor(text: string, userId: string) {
this.text = text;
this.userId = userId;
}
}
class TmpTask {
userId: string;
tasks: Task[];
constructor(userId: string) {
this.userId = userId;
this.tasks = [];
}
}
const tasks: Task[] = [];
tasks.push(new Task('Send a mail now!!', 'bob'));
const tmpTasks: TmpTask[] = [];
for (let task of tasks) {
console.log("task: ", task);
const index = tmpTasks.findIndex( (_tmpTask, _index, _tmpTasks) => {
return _tmpTask.userId === task.userId;
});
tmpTasks[index].tasks.push(task);
}
console.log("tmpTasks: ", tmpTasks);
此代码运行时,将导致以下错误。
Uncaught TypeError: Cannot read property 'tasks' of undefined
at _loop_1 (<anonymous>:23:21)
at <anonymous>:27:5
at HTMLButtonElement.excuteButton.onclick (http://www.typescriptlang.org/play/playground.js:247)
我不知道如何解决。
您能给我任何建议吗?