Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  67] [ 3]  / answers: 1 / hits: 191258  / 12 Years ago, mon, december 10, 2012, 12:00:00

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);

More From » javascript

 Answers
51

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<array.length; i++){
if (array[i]>largest) {
largest=array[i];
}
}




console.log(largest);

[#81517] Friday, December 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeffery

Total Points: 180
Total Questions: 114
Total Answers: 117

Location: Chad
Member since Mon, Dec 5, 2022
2 Years ago
jeffery questions
Fri, Jan 22, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
Mon, Feb 10, 20, 00:00, 4 Years ago
;