【发布时间】:2022-01-03 15:06:18
【问题描述】:
在我的TaskList 类中,我有一个名为sortByWhenDue 的方法,它应该按到期日期和时间对_tasks 属性中的Task 对象进行排序(即Date 对象存储在_whenDue 属性中)从最早到最晚。但是,当我尝试使用它时,我收到错误消息Uncaught TypeError: Cannot read properties of undefined (reading '_whenDue')。有谁知道我应该怎么做?谢谢。
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.length为真时,您的循环将继续。所以如果长度是10(比如说),在最后一个循环上i是9。所以在if (this._tasks[i]._whenDue > this._tasks[i+1]._whenDue) {中,i + 1是10和this._tasks[10]是undefined,因为你已经过了数组的末尾(带有length = 10的数组在索引0到9有条目)。 -
解决此类问题的最佳方法是使用内置在 IDE 和/或浏览器中的调试器来单步执行代码并在执行逻辑时查看事物的值。
标签: javascript class methods bubble-sort