簡體   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