dimanche 4 février 2018

JavaScript: if statement inside for loop (finding largest number from array)

I'm having trouble understanding how this code was able to find the largest number from an array of numbers. This is what I understand so far:

1) declared variable, i, and assigned it the value of 0.
2) for loop: x starts at 0, but will increment for as long x < integers.length (which would be 5?) so we would be talking about x = 0 --> 4
3) the if statement is where I'm confused. "integers" is the parameter, but the argument we pass to it is an array. So in my head, I'm seeing [5, 10, 21, 6, 100][x] > i, which I know makes no sense.

let i = 0;

function findLargest (integers) {
  for (let x=0; x<integers.length; x++) {  
    if (integers[x] > i) {     
      i = integers[x];
    }
  }
  console.log(i);
}

findLargest([5, 10, 21, 6, 100]);          
//Output: 100 

Aucun commentaire:

Enregistrer un commentaire