0

this is the code I am writing atm:

var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
for (var i = 0; i < array.length; i++){
 if ( i > largest) {
 i = largest;
 }
}
console.log(largest);

It should be alerting the largest number in the array, but it seems to be stuck in an infinite loop.

asked Mar 20, 2013 at 23:02
3
  • 2
    you shouldn't change i! Commented Mar 20, 2013 at 23:03
  • never change i in a for loop, and you are not doing anything with the array in the loop Commented Mar 20, 2013 at 23:05
  • largest = i > largest ? i : largest; Commented Mar 20, 2013 at 23:07

5 Answers 5

4

I think you want

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

Basically you are saying "if i is greater than 0, set i to 0", which will cause i to alternate between 0 and 1 forever.

answered Mar 20, 2013 at 23:04
Sign up to request clarification or add additional context in comments.

Comments

3
var arr = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = arr[0];
for (var i = 0; i < array.length; i++){
 if ( arr[i] > largest) {
 largest = arr[i];
 }
}
console.log(largest);
answered Mar 20, 2013 at 23:04

3 Comments

It should be var largest = arr[0]
It should be set to arr[0]
well this shouldn't make any difference but you're right. that's better.
2

I think you meant.

var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = array[0];
for (var i = 1; i < array.length; i++){
 if ( array[i] > largest) {
 largest = array[i];
 }
}
console.log(largest);
answered Mar 20, 2013 at 23:04

Comments

1

You are resetting the value of i every time you find a new largest, so that you have the infinite loop. This line makes your loop infinite:

i = largest;
paddy
63.7k7 gold badges68 silver badges109 bronze badges
answered Mar 20, 2013 at 23:04

Comments

0

You can find max value of array using

Math.max.apply(null, array)
answered Mar 20, 2013 at 23:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.