簡體   English   中英

我的程序不斷收到此錯誤:VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined

[英]I keep getting this error for my program: VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined

我正在嘗試使用 HTML 和 Javascript 直觀地實現合並排序算法。 我的 Merge Sort Implementation 輸出按計划工作,但我的終端窗口中不斷出現錯誤。

//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }


//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

這是我在控制台中的錯誤圖片

控制台錯誤

您收到錯誤是因為在sort函數中undefined smallTwo

完整的錯誤消息是:

while (smallOne.length && smallTwo.length) {
                                       ^

TypeError: Cannot read property 'length' of undefined

缺少第二個參數

 mergeSort = (array) => { return sort(divide(array), ????) }

我想你可以叫從歸並鴻溝,由於某種期待兩個變量和歸並排序呼叫與單個參數已經排序輸出終於打來電話..

 mergeSort = (array) => { return divide(array); }

您在對數組進行排序后再次調用排序

並且第二個數組 smallTwo 變得未定義

您可以在 while 迭代器之前檢查它是否未定義

if (!smallTwo) {
    smallTwo = []
}

那可以解決你的問題

或者像這樣在第一次調用中發送一個空數組

mergeSort = (array) => {
return sort(divide(array), [])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM