Samstag, 14. Mai 2016

Javascript Beginner's Array Exercises: Evaluate the existance of a specific element in an array

Now we search a specific array element an array of integers. The element we search for is stored in the variable V.
In Javascript, there is a function that provides just that functionality: indexOf. indexOf returns the index of the searched for element. If the array does not contain the element, indexOf would return -1. For more information, see: http://www.w3schools.com/jsref/jsref_indexof_array.asp

However, the task is to get used to traverse and work with arrays. So in this video we won't use indexOf, but we will search for the array element manually.



Here is the relevant source code:

var arNums = [76,42,2,3,5,6,2,56,777,9,0,5,2,56,1];
var V = 716;

var foundV = false;
for(let i = 0; i < arNums.length && foundV==false; i++) {
  if(arNums[i] == V) {
    foundV = true;
  }
}


You can also check for the existance of the element using indexOf like this:

if (arNums.indexOf(V) > -1) {
   foundV = true;
} else {
   foundV = false;
}

You can even abbreviate that 5 lines above like this:

foundV = (arNums.indexOf(V) > -1);

Why does this work? arNums.indexOf(V) > -1 is an expression that yields true or false, which is just what we want the variable foundV to contain. So we can write the result of that expression directly in our variable.

Keine Kommentare:

Kommentar veröffentlichen