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>