简体   繁体   中英

array.push() does not work even though array object is clearly defined and in scope

I have the following simple JavaScript code (merge sort) and for some reason pushing values to an array isn't working inside the merge() function (lines 26 and 31 in the jsfiddle). Is it something about the scope of the array? But it's clearly defined inside the merge function. I am missing something very conceptual here. Any help would be greatly appreciated.

https://jsfiddle.net/kalyanc/pu8988qc/

var A = [5,2,4,7,1,3,2,6];      

mergeSort(A);

function mergeSort(array) {
  if (array.length < 2) {
    return array;
  }
  var midpoint = parseInt(array.length/2);
  var left = array.slice(0, midpoint);
  var right = array.slice(midpoint, array.length);
  alert("Calling merge with arrays, " + left + " and " + right);
  return merge(mergeSort(left), mergeSort(right));
}

function merge(L, R) {
  var Output = []; // Output array is clearly defined here.

  var m = 0;
  var n = 0;

  while(m < L.length && n < R.length)
  {
    for (var x = 0; x < Math.min(L.length, R.length); x++) {
      if (L[m] <= R[n]) {
        Output.push(L[m]); // Does not work! 
        m++;        
        alert("Output from merge is array " + toString(Output)); 
        // Alerts: Output from merge is array [object Undefined]
      } else {
        Output.push(R[n]); // Does not work!
        n++;
        alert("Output from merge is array " + toString(Output));
        // Alerts: Output from merge is array [object Undefined]
      }             
    }
  }         

  // Check if either L or R have an element left
  if (m < L.length) {
    for (var o = m; o < L.length; o++) {                    
      Output.push(L[o]);
    }               
  }
  if (n < R.length) {
    for (var o = n; o < R.length; o++) {
      Output.push(R[o]);
    }               
  }
  return Output;                    
}

toString is an Object prototype function, and should be called on an object.

In your particular instance, instead of calling toString(Output) try using Output.toString() .

jsfiddle

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