As a newcomer to JavaScript and StackOverflow, I am currently working on creating a function to search for a specific value within an array I have created. Although I have written what I think is a functioning function, it seems to not be working. Any ideas or obvious flaws you can spot? Thanks!
HTML:
<td>Index: <input style = "width: 50px" input type ="textbox" id="Index" value="2"/></td> <!-- HTML code to create the index textbox -->
<br/> <!-- Line Break -->
Value: <input style = "width: 50px" input type = "textbox" id="Value" value = "10"/> <!-- HTML code to create the value textbox -->
<br />
<td>Enter Value to Find: <input style="width: 50px;" type="textbox" value="20" />
<input type="button" value="Search Array" onClick = searchArray(); /></td>
<br />
<input type = "button" value = "Create" onClick = "createArray();"/>
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<div id="result">
JS:
var myArray = [];
var d = ""; //This global variable is going to be used for clearing and populating the screen
function createArray (){
//This functions is to clear the current information on the screen so the array can populate
clearScreen();
//The next thing we want to do according to the lecture is create a FOR loop to run 100 times to set the various array values
for (var i = 0; i <100; i++){
myArray[i] = Math.floor(Math.random()* 100 + 1); //Math.floor rounds an number downards to the nearest integer then returns. Math.random returns a integer randomly withing given variables
}
popScreen(); //function to fill the screen with the array
}
function clearScreen(){
d = ""; //Global string variable mentioned before
document.getElementById("result").innerHTML = "";
}
function popScreen(){
for (var i = 0; i < myArray.length - 1; i++){
d += i + ' : ' + myArray[i] + "<br/>";
}
document.getElementById("result").innerHTML = d;
}
function insertIntoArray(){
clearScreen();
var i= parseInt(document.getElementById("Index").value);
var j = parseInt(document.getElementById("Value").value);
d = "inserting " + j+ " at " + i + "<br/>";
var temp = myArray[i];
for (i; i < 100; i++) {
myArray[i] = j;
j = temp
temp = myArray[i+1];
}
popScreen();
}
**function searchArray(myArray, value){
var searchResult = 0;
var searchIndex = -1;
for(var i = 0; i<myArray.length; i++){
searchResult++;
if(myArray[i] == value){
searchIndex = i;
break;
}
}
if (searchIndex == -1){
console.log("Element inquiry not found in array. Total Searched: " + searchResult);
}else{
console.log("Element found at index: " + searchIndex + ", search count: " + searchResult);
}**
}