简体   繁体   中英

Can someone explain to me why this loop doesn't give me the desired result?

Basically, I'm writing a little algorithm that takes in a random array with only numbers and spits out the 2nd highest number in the array (assuming all entries in the array are numbers and there are at least 2 entries). Here is the code:

var secondGreatest = function(numberArray){

  var array = numberArray;
  var result = [];

  for(var i = 0; i < array.length; i++){

      if(array[i] === Math.max.apply(Math, array)){
        result.push(array[i]);
        array.splice(i, 1);
      }
  };

  return result[1];

};

So what I'm doing is setting the input array of numbers to variable "array". Then I set variable "result" to an empty array.

In the for loop, I specify that if the array at the ith position equals the highest number of the array, push that number into the empty array and remove that number from the original array. Since the "result" array will have the order from highest to lowest number, I call result[1] to give me the 2nd highest number.

However, the result array only contains one entry and it's the highest number of the previous array. After that, the for loop seems to stop. I tried the "continue;" statement, but nothing works.

Any help as to why this doesn't work is appreciated.

Here is a shorter code, if you want to keep using the Math.max method.

var secondGreatest = function(numberArray){
  var top1 = Math.max.apply(Math, numberArray);
  numberArray.splice(numberArray.indexOf(top1));
  return Math.max.apply(Math, numberArray);
};

var arr = [1,3,5,7,4,2];
alert(secondGreatest(arr));

You don't really need to iterate, and actually iterating would make it necessary to reset the for whenever you remove the max item. Tushar's answer in the comment is more compact though, and problably makes more sense.

When you do a splice, the array is being re-indexed and array.length which was cached becomes obsolete. This is why the for loop stops. You can start at the end and iterate backwards to fix this.

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