javascript - 我的程序不断收到此错误 : VM178 SortLib. js:71 Uncaught TypeError: 无法读取未定义的属性 'length'

标签 javascript html arrays

我正在尝试使用 HTML 和 Javascript 直观地实现合并排序算法。我的合并排序实现的输出按计划工作,但我不断在终端窗口中收到错误。

//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))
}

这是我在控制台中出现的错误的图片

Console Error

最佳答案

您收到错误是因为 smallTwosort 函数中是 undefined

完整的错误消息是:

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

TypeError: Cannot read property 'length' of undefined

关于javascript - 我的程序不断收到此错误 : VM178 SortLib. js:71 Uncaught TypeError: 无法读取未定义的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60264574/

相关文章:

JavaScript 只允许用户点击一次

javascript - 仅在鼠标悬停时在 Canvas 上显示文本

javascript - 根据下拉菜单中的选择显示/隐藏表单域

java - 自动迷宫解决方案

javascript - JavaScript闭包如何工作?

javascript - 除了使用 Date.parse() 之外的选项

javascript - 当我右键单击网格标题时,菜单未显示

jquery - 在 Wordpress 中创建全屏覆盖窗口

c - 这个保存的数组与加载的数组有什么不同?

java - 查找数组中第二小的整数