+ 6

Help me please with this piece of code

I tried to create a simple function finding the largest number in an array, but it doesn't work. Alert displays "0" intead of "34" var array = [1, 34, 5, 2, 32, 1]; var x = max(array); alert(x); function max(array){ var maxNum = 0; var i; for(i = 0; i<array.length; i++){ if(array[i]< maxNum){ maxNum = array[i]; } } return maxNum; }

12th Jun 2018, 10:08 AM
Ulyana Sveleba
Ulyana Sveleba - avatar
3 Respostas
+ 4
Donna KrOW thankyou for your help ☺
12th Jun 2018, 11:11 AM
Ulyana Sveleba
Ulyana Sveleba - avatar
+ 2
I want add that your code dont handle all negative integers array ex. [-3, -10, -5] you have to set maxNum to first item vaule (handling empty array if necessary) and do checking loop from second item
12th Jun 2018, 11:08 AM
KrOW
KrOW - avatar