Array Creation

by vzufelt

HTML

Index:
<input type="textbox" id="index" value="2" />
<br/> Value:
<input type="textbox" id="value" value="10" />
<br/> Search:
<input type="textbox" id="search" value="10" />
<br/>
<input type="button" value="Create Array" onClick="fillArray();" />
<br/>
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<br/>
<input type="button" value="Search Array" onClick="searchArray()" />
<br/>
<div id="searched">

</div>

<div id="output">

</div>

JavaScript

// global vars
var array = [];
var d = "";
var b = "";
var c = "";
// operations counter
var count = 0;


// function to fill the array with 100 elements
function fillArray() {
  // clears the display area
  clearDisplay();
  // loop to create 100 random elements in the array
  for (var i = 0; i < 101; i++) {
    array[i] = Math.floor(Math.random() * 100 + 1);
  }
  // displays the array just made
  displayArray();
}

// function to clear the display
function clearDisplay() {
  // makes d have display
  d = "";
  // used to display output and searched 
  document.getElementById("output").innerHTML = "";
  document.getElementById("searched").innerHTML = "";
}

//function to display the created array
function displayArray() {
  // loop to add the array values to d
  for (var i = 0; i < array.length - 1; i++) {
    d += i + ' : ' + array[i] + "<br/>";
  }
  document.getElementById("output").innerHTML = d;
}

//function to add value at index 
function insertIntoArray() {
  clearDisplay();
  // get value of index of value to insert
  var t = parseInt(document.getElementById("index").value);
  // get actual value to insert at index i
  var v = parseInt(document.getElementById("value").value);

  d = "Inserting " + v + " at " + t + "<br/>";
	
  // used to keep the array at 100, takes one off.
  for (i = array.length - 2; i >= t; i--) {
    count++;
    array[i + 1] = array[i];
  }
  d = "You have done " + count + " operations.<br/>";
  array[t] = v;
  displayArray();

}

// function to search array for value and show its index
function searchArray() {

	// var a equals the value put in at search
  var a = parseInt(document.getElementById("search").value);
  var count = 0;

	// loops through array to find when searched value equals array
  for (i = 0; i < array.length; i++) {
    count++
    if (array[i] == a) {
    	var g = i;
      b = a + " found " + " at " + g + "<br/>";
      count++;
      break;
  }
  }
	// displays what index the value was found at
 ...