繁体   English   中英

JavaScript中的冒泡排序方法

[英]Bubble sort method in JavaScript

在我的TaskList class 中,我有一个名为sortByWhenDue的方法,它应该按照它们到期的日期和时间(即存储在_whenDue属性中的Date object)从最早到最晚对_tasks属性中的Task对象进行排序。 但是,当我尝试使用它时,我收到错误消息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);
    }
}

this._tasks[i+1]是问题所在。 如果您到达 for 循环的末尾,您的代码会尝试访问不存在的索引。 所以undefined返回并且您的代码尝试从undefined获取_whenDue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM