简体   繁体   中英

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. So if it indexes 1 --> 4, they will all still be greater than 0.

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 

What doesn't make sense? That is called array indexing (getting a value from the array by specifying the index). The syntax is array[index]

So, if you have an array, say

 var arr = [10, 6, 15]

You can access it's second element via

arr[1] // 6

The array doesn't need to be stored in a variable. Arrays are values (moreover, they are objects). So [10, 6, 15][1] has the exact same effect as in the example above.

In your case, integers[x] will be the element at the position x. Using a for 0 to length - 1 loop is a way of iterating over an array. That function goes through every element in the array and verifies if the element is greater than the last element found. This way, it finds the greatest

Note: The algorithm you have is not complete because it will fail for an array where all elements are less than 0. In such cases, the search should not start from an arbitrary value (in your case 0), but from an existing element of the array (usually the first). Also, calling the function multiple times fails because the variable x is global and not local to the function. I suggest removing the very first line of your code and adding a new line at the start of the function:

 var i = integers[0]

Update (After OP has edited the question) Yes, they will all be greater than 0, but you are not searching for greater than 0 every time . The line

 i = integers[x]

changes the value of I to the element that was found to be greater than 0 at first. So the next serch will be for greater than that element. It looks like this. Let's take this array: [5, 7, 2, 12, 0]

5 > 0  (TRUE) => i = 5
7 > 5 (TRUE)  => i = 7
2 > 7 (FALSE)
12 > 7 (TRUE) => i = 12
0 > 12 (FALSE)

You could take the array with indices and go to every value and check and look which value is taken for the comparison and which value changes.

In the loop, you could add console.log with index, both values to compare, the compare result and the new value of i if changed, like

console.log(x, array[x], i, array[x] > i, array[x] > i && array[x])
 [5, 10, 21, 6, 100][x] > i 

with values

 [5, 10, 21, 6, 100][0] > 0 5 > 0 -> i = 5 [5, 10, 21, 6, 100][1] > 10 10 > 5 -> i = 10 [5, 10, 21, 6, 100][2] > 21 21 > 10 -> i = 21 [5, 10, 21, 6, 100][3] > 6 6 > 21 [5, 10, 21, 6, 100][4] > 100 100 > 21 -> i = 100 

 function findLargest(integers) { var i = integers[0], // take the first element of the array x; for (x = 1; x < integers.length; x++) { // iterate from the second element console.log(x, integers[x], i, integers[x] > i, integers[x] > i && integers[x]); if (integers[x] > i) { i = integers[x]; } } return i; } console.log(findLargest([5, 10, 21, 6, 100])); 

You could also use reduce instead of a loop.

function findLargest (integers) {
  if(integers.length===0){
    return;//return undefined for empty array since there is no lowest
  }
  return integers.reduce(
    function(highest,current){
      return (current>highest)
        ? current
        : highest
    }
  );;
};
findLargest([5, 10, 21, 6, 100]); 

For many processes that can be solved with reduce you can also use recursion :

function findLargest (integers) {
  var recur = function(highest,numbers){
    if(numbers.length===0){//processed all numbers, return highest
      return highest;
    }
    if(numbers[0]>highest){
      highest=numbers[0];
    }
    //call itself again with highest and numbers without the first element
    return recur(highest,numbers.slice(1));
  };
  //return recursive function recur
  return recur(integers[0],integers.slice(1));
};
findLargest([5, 10, 21, 6, 100]); 

A not very effective way but smallest amount of code (would not advice doing this for code that uses large arrays or is called many times with smaller ones).

This uses the mutator method called sort .

function findLargest (integers) {
  //map integers so you have a copy of integers
  //  this because .sort is a mutator methods and will
  //  change integers if you don't copy it first
  return integers.map(x=>x).sort((a,b)=>a-b).slice(-1)[0];
};
findLargest([5, 10, 21, 6, 100]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM