简体   繁体   中英

Don't know why the length is undefined

I am not sure why, but for some reason when I execute the code it says that the length of the array right is undefined, but why is right undefined? In the execution of this code, I get this error:

" while (result.length < (left.length + right.length)) { ^

TypeError: Cannot read property 'length' of undefined"

function merge(left, right) {
  var result = [], iLeft = 0, iRight = 0;

  while (result.length < (left.length + right.length)) {
    if (iLeft === left.length) result = result.concat(right.slice(iRight));
    else if (iRight === right.length) result = result.concat(left.slice(iLeft));
    else if (left[iLeft] <= right[iRight]) result.push(left[iLeft++]);
    else result.push(right[iRight++]);
  }
  return result;
}


function mergeSortRecursive (array) {
  // base case
  if (array.length <= 1) return array;

  // divide and conquer!!
  var leftHalf = array.slice(0, array.length/2);
  var rightHalf = array.slice(array.length/2);
  var leftSorted = mergeSortRecursive(leftHalf);
  var rightSorted = mergeSortRecursive(rightHalf);

  // merge subarrays
  return merge(leftSorted, rightSorted);
};

merge(sampleArr); 
console.log(sampleArr);

   

When calling the merge function, you are not supplying the needed parameters, as in it's declaration you ask for two parameters, and when using it, you are supplying one only, as stated by Jeremy .

Plus, I would recommend the use of let instead of var , as it makes variables more secure to work limiting it's scope to the block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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