1

That script that I am working on is supposed to be rather simple. The user is presented with two buttons. One to type their own input into an array. Once this array has been created it is automatically sorted. A second button allows the user to search for any number that may or may not be in the array. This is where my problem begins.

What is supposed to happen is that when the user inputs the number they want to find. The array is searched for that number. If the number exists in that array then a message saying that the number has been found appears. If the number is not found then a message stating so will appear.

I feel like the problem is with the for loop in my search function. Unfortunately I have yet to come across a solution on my own. When I ran my code in the snippet submission I got the following error.

{
  "message": "Uncaught TypeError: Cannot read property 'length' of undefined",
  "filename": "http://stacksnippets.net/js",
  "lineno": 65,
  "colno": 16
}

The most current version of the script has been inserted for reference. Any help is appreciated and thanks in advance.

/* Array Function */
function arrayFunction() {
  var arr = [];
  for (var i = 0; i < 5; i++)
    arr.push(prompt("Enter a number"));

  bubbleSort(arr);
  console.log(arr);

  arr.toString();
  window.confirm("Your sorted array is: " + arr).innerHTML = arr;
}

/* Sort Function */
function bubbleSort(arr) {
  var swapped;
  do {
    swapped = false;
    for (var i = 0; i < arr.length - 1; i++) {
      if (arr[i] > arr[i + 1]) {
        var temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);
}

/* Search Function */
function numSearch(arr) {
  var x = window.prompt("Search for a number.");
  for (var i = 0; i < arr.length; i++); {
    if (arr[i] == x) {
      return window.confirm("It's here.");
    }
  }
  return window.confirm("It is not here.")
}
<html>
<head>
</head>
<body>
  <script language="JavaScript">
  </script>
  <button type="button" onclick="arrayFunction()">Create Array</button>
  <button type="button" onclick="numSearch()">Search Array</button>
</body>
</html>

3 Answers 3

1

UPDATE: There are two issues: One is that arr is not defined in your function. The other is that you have a semicolon directly following your numSearch for loop, causing it to terminate early and never iterate your results. As an aside, I'd recommend parsing the strings to numbers and using strict equality as shown in this example.

In addition, you could increase the efficiency of your algorithm from O(N^2) down to O(N log N) by switching from bubble sort to merge sort.

The following code snippet works:

/* Array Function */
let arr = [];
function arrayFunction() {
  arr = [];
  for (let i = 0; i < 5; i++) {
    arr.push(parseInt(prompt("Enter a number")));
  }

  bubbleSort();
  console.log(arr);

  arr.toString();
  window.confirm("Your sorted array is: " + arr).innerHTML = arr;
}

/* Sort Function */
function bubbleSort() {
  var swapped;
  do {
    swapped = false;
    for (let i = 0; i < arr.length - 1; i++) {
      if (arr[i] > arr[i + 1]) {
        var temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);
}

/* Search Function */
function numSearch() {
  var x = parseInt(window.prompt("Search for a number."));
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === x) {
      return window.confirm("It's here.");
    }
  }
  return window.confirm("It is not here.")
}
<html>
<head></head>
<body>
  <button type="button" onclick="arrayFunction()">Create Array</button>
  <button type="button" onclick="numSearch()">Search Array</button>
</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

It's because arr is defined inside the function arrayFunction thus accessible only within its scope. If you want to be able to access it in other functions such as numSearch you'll have to make it global. Declaring it as an argument and calling the function with no parametter will not solve the problem. Try this structure:

var arr = []; // arr is gloabal now it can be accessed by all other functions bellow it

function arrayFunction() {
  //var arr = []; // remove this line
  // ...
}

function bubbleSort(arr) {
  // ...
}

function numSearch(arr) {
  // ...
}

Comments

0

There were 2 problems.

The first is that the arr was being made but as soon as the function was done running, it would get destroyed.

The second issue was that you have a semicolon ; between the for and the bracket {.

/* Array Function */
var main_array = []; // <-------------------------------------add this.

function arrayFunction() {
  var arr = [];
  for (var i = 0; i < 5; i++)
    arr.push(prompt("Enter a number"));

  bubbleSort(arr);
  console.log(arr);

  arr.toString();
  window.confirm("Your sorted array is: " + arr).innerHTML = arr;

  main_array = arr; // <-------------------------------------add this.
}

/* Sort Function */
function bubbleSort(arr) {
  var swapped;
  do {
    swapped = false;
    for (var i = 0; i < arr.length - 1; i++) {
      if (arr[i] > arr[i + 1]) {
        var temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);
}

/* Search Function */
function numSearch() { // <------------------------------------remove `arr`
  var x = window.prompt("Search for a number.");
  var arr = main_array; // <-----------------------------------add this.
  for (var i = 0; i < arr.length; i++) { // <------------------remove  semicolon.
    if (arr[i] == x) {
      return window.confirm("It's here.");
    }
  }
  return window.confirm("It is not here.")
}
<html>
<head>
</head>
<body>
  <script language="JavaScript">
  </script>
  <button type="button" onclick="arrayFunction()">Create Array</button>
  <button type="button" onclick="numSearch()">Search Array</button>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.