I deduce the maximum number by function.

var myArray = [0, 1, 9, 4, 3, 2, 8, 6]; var result = myArray[0]; function maxResult(data) { for (i = 0; i < data.length; i++) { if (data[i] > data[0]) { data[0] = data[i]; console.log(data[0]); } } } maxResult(myArray); 

As a result, in the console, I get the result 1 and 9. I can not understand what the problem is.

Please do not rush slippers, while still studying javascript.

Thanks for answers. The question is closed.

  • one
    because you are console.log() through console.log() . 1> 0, 9> 1, then all the numbers are smaller. take console.log() over the loop. - Alex
  • pay attention. that you spoil the original array by changing its first value to the maximum - Grundy
  • Yes, I noticed it. Already fixed. - Masha Bubble

2 answers 2

The result must be output after the cycle, because in the loop, you only output intermediate results

    You output to the console in the body of the loop, after

     var myArray = [0, 1, 9, 4, 3, 2, 8, 6]; var result = myArray[0]; function maxResult(data) { for (i = 0; i < data.length; i++) { if (data[i] > data[0]) { data[0] = data[i]; } } console.log(data[0]); } maxResult(myArray); 

    • @nick_n_a in this case there would be no answer to the question - etki