Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  132] [ 3]  / answers: 1 / hits: 45422  / 12 Years ago, wed, october 31, 2012, 12:00:00

Well, I like to not just memorize blocks of code, but to understand them, so that I can create them myself. Why does this work? I don't understand. If someone can explain it to me, I'd be most grateful. To me it looks like: If the array index (position in the array) is greater than 0, 0 = the array index, and how that would magically tell me the highest number in the array I haven't a single clue. I've tried searching for an answer on this but without luck. Here's an example of the code, thanks in advance:



var array = [3, 4, 5, 21.15, 21, 9];
var largest = 0;

for (i = 0; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
console.log(largest);​

More From » javascript

 Answers
9

The line largest = array[i]; does NOT mean 0 = array[i] as you believe. largest is a variable, so each time you get to the line largest = array[i]; you are changing the value of largest to be the current array[i].



This is why you get the max of the array at the end.



An example: a = [1, 3, 7, 2]



You initialize largest = 0. The, for each element of the array you do the following:



largest < 1? yes, so largest = 1
largest < 3? yes, so largest = 3
largest < 7? yes, so largest = 7
largest < 2? no, so do nothing

[#82261] Monday, October 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;