[英]I keep getting this error for my program: VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript.我正在尝试使用 HTML 和 Javascript 直观地实现合并排序算法。 My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.
我的 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))
}
Here's a picture of my error in the console这是我在控制台中的错误图片
You are getting the error because that smallTwo
is undefined
inside the sort
function.您收到错误是因为在
sort
函数中undefined
smallTwo
。
The Full error message is:完整的错误消息是:
while (smallOne.length && smallTwo.length) {
^
TypeError: Cannot read property 'length' of undefined
Second parameter is missing缺少第二个参数
mergeSort = (array) => { return sort(divide(array), ????) }
I think you can just call divide from mergeSort , As sort is expecting two variables and the sort call in mergeSort is called finally with already sorted output with a single parameter ..我想你可以叫从归并鸿沟,由于某种期待两个变量和归并排序呼叫与单个参数已经排序输出终于打来电话..
mergeSort = (array) => { return divide(array); }
you are calling the sort one more time after the array is being sorted您在对数组进行排序后再次调用排序
and the second array which is smallTwo become undefined并且第二个数组 smallTwo 变得未定义
you can check if its undefined before your while iterator您可以在 while 迭代器之前检查它是否未定义
if (!smallTwo) {
smallTwo = []
}
that could solve you problem那可以解决你的问题
or just send an empty array in your first call like this或者像这样在第一次调用中发送一个空数组
mergeSort = (array) => {
return sort(divide(array), [])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.