Possible Duplicate:
How might I find the largest number contained in a JavaScript array?
I am having trouble getting this code to work. I have been at it for a while trying to figure it out. When I look at the console it just displays 0. What did I do wrong?
Here is my code:
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;
for (i=0; i<=largest;i++){
if (array>largest) {
var largest=array[i];
}
}
console.log(largest);
var arr = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = arr[0];
for (var i = 0; i < arr.length; i++) {
if (largest < arr[i] ) {
largest = arr[i];
}
}
console.log(largest);
i
or else it become a global variable.i < array.length
instead of i <= largest
.largest
, use if(largest < array[i])
instead of if(array > largest)
array
is a bad variable name because it's too similar to Array
(the array constructor). Try arr
instead.One liner:
var largest = Math.max.apply(0, array);
More info here: Javascript max() function for 3 numbers
The code below is fixed and should work. The problem was that in this line if (array>largest) {
You were not providing the index of the array. By changing the code to this if (array[i]>largest) {
it works. Notice that I added the [i]
to the end of array
in the if statement.
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;
for (i=0; i<=largest;i++){
if (array[i]>largest) {
var largest=array[i];
}
}
console.log(largest);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With