Unable to compare negative numbers in array | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Unable to compare negative numbers in array

Hello, I made a small code trying to find the largest and smallest number in an array. However, it seems like the program refuse to execute the first condition I set, can someone help to advise on this please? function differenceMinMax(array) { for (var i = 0; i < array.length; i++) { if (array[i+1]< array[i]) { console.log("test"); } } } differenceMinMax([-5,0,3]); Regards Ben

11th Dec 2019, 1:17 AM
Ben
2 Antworten
0
array[i+1] is trying to find non-exist value at the last loop For your example, array length is 3 so last index is 2 ..if(array[3]<array[2]).. but there isn't array[3] You should avoid this for(var i=0; i<array.length-1; i++)
11th Dec 2019, 5:23 AM
Mystic Life
Mystic Life - avatar
0
thank you!
14th Dec 2019, 2:23 PM
Ben