Undefined is not an object (estimate myArray.length)

I was working on a program that uses a fast sorting algorithm to sort an array of numbers. This is my code:

    var myArray=[8,2,5,6];

function quickSort(myArray)
{
    if (myArray.length === 0){
        return [];
    }

    var left=[];
    var right=[];
    var pivot= myArray[0];

    for (var i=1; i<myArray.length; i++){

        if (myArray[i]<pivot) {
            left.push(myArray[i]);

        }

        else {

            right.push(myArray[i]);
        }
    }

    return quickSort(left).concat(pivot, quickSort(right));
    document.getElementById().innerHTML = quickSort(left).concat(pivot, quickSort(right));
}

      

And here is my html

<html>
<h1>QuickSorter</h1>
<button onclick="quicksort()">Quick Sort It!</button>
<script src="quicksort.js"> </script>
</html>

      

The safari console keeps showing me the following:

TypeError: undefined is not an object (evaluating myArray.length)

      

I really don't understand why it doesn't work. Any help would be appreciated.

+3


source to share


2 answers


If you call the function with

quicksort()

      

you don't pass any arguments. However, your function starts with

function quickSort(myArray)
{
  if (myArray.length === 0){
    return [];
  }

      

Since no arguments quicksort

are passed, it myArray

remains undefined. Undefined variables are not objects and therefore cannot have properties like length

.

EDIT:



To call the function when you click the button, your best bet is to set an event listener in javascript rather than putting it in your HTML.

Give the button an ID name and remove the attribute onclick

:

<button id="sortButton">Quick Sort It!</button>

      

Then add an event listener to your JavaScript after the definition quicksort

:

document.getElementById("sortButton").onclick = function(){quickSort(myArray);});

      

+6


source


You are not passing a function parameter to your html onclick. Therefore myArray turns out to be undefined inside your function. Note that the myArray that u defined outside the function is not the same myArray inside it that is defined as the tp parameter, the function



+3


source







All Articles