I was wondering if anyone can somebody please explain to me how this loop works?.
for (var x = 0; x < numbers.length; x++) {
if (numbers[x] > largest)
largest = numbers[x];
}
}
I was wondering if anyone can somebody please explain to me how this loop works?.
for (var x = 0; x < numbers.length; x++) {
if (numbers[x] > largest)
largest = numbers[x];
}
}
Here is an explanation of everything happening in the for loop
// keeps the for loop going while x is less than numbers.length which is the length of nmbers
// sets x to 0 initialy | increases x by +1 each time it restarts to begin the loop
// V V V
for (var x = 0; x < numbers.length; x++) {
// Executes code if numbers[x] is greater than largest
// V
if (numbers[x] > largest){
// sets largest to numbers[x] if numbers[x] is greater than largest
// V
largest = numbers[x];
}
}
I think you are trying to get the largest number from the array, so here is how I would do it:
// https://stackoverflow.com/questions/1669190/javascript-min-max-array-values
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
document.write(array.max());