In my TaskList class, I have a method called sortByWhenDue which is supposed to sort the Task objects in the _tasks attribute by the dates and times they are due (i.e. the Date object stored in the _whenDue attribute) from earliest to latest. However, when I try to use it, I get the error message Uncaught TypeError: Cannot read properties of undefined (reading '_whenDue'). Does anyone know what I should do about this? THanks.
class Task
{
/**
* @param {String} taskName a short description of the task
* @param {String} category the category of the task
* @param {Date} whenDue when the task is due
*/
constructor(taskName, category, whenDue) {
this._taskName = taskName;
this._category = category;
this._whenDue = whenDue;
}
get taskName() {
return this._taskName;
}
get category() {
return this._category;
}
get whenDue() {
return this._whenDue;
}
set taskName(newTaskName) {
if (typeof newTaskName === 'string') {
this._taskName = newTaskName;
}
}
set category(newCategory) {
if (typeof newCategory === 'string') {
this._category = newCategory;
}
}
set whenDue(newWhenDue) {
if (typeof newWhenDue === 'object') {
this._whenDue = newWhenDue;
}
}
fromData(data) {
this._taskName = data._taskName;
this._category = data._category;
this._whenDue = data._whenDue;
}
}
class TaskList
{
constructor() {
this._tasks = [];
}
get tasks() {
return this._tasks;
}
addTask(task) {
if (typeof(task) === 'object') {
this._tasks.push(task);
}
}
getTask(taskIndex) {
return this._tasks[taskIndex];
}
fromData(data) {
this._tasks = [];
for (let i = 0; i < data._tasks.length; i++) {
let tempName = data._tasks[i]._taskName;
let tempCategory = data._tasks[i]._category;
let tempWhenDue = new Date(data._tasks[i]._whenDue);
let tempTask = new Task(tempName, tempCategory, tempWhenDue);
this._tasks.push(tempTask);
}
}
sortByWhenDue() {
do {
let swapped = false;
for (let i = 0; i < this._tasks.length; i++) {
if (this._tasks[i]._whenDue > this._tasks[i+1]._whenDue) {
let temp = this._tasks[i+1];
this._tasks[i+1] = this._tasks[i];
this._tasks[i] = temp;
swapped = true;
}
}
} while (swapped);
}
}
i < this._tasks.lengthis true. So if the length is10(say), on the last loopiis9. So inif (this._tasks[i]._whenDue > this._tasks[i+1]._whenDue) {,i + 1is10andthis._tasks[10]isundefinedbecause you've gone past the end of the array (an array withlength = 10has entries at indexes0through9).