Javascript while loop with if statements

21,798

Solution 1

Implement a counter so you can access the values in the array.

var i = 0;
while(numbers.length < 5 && i < numbers.length)
{
    if(numbers[i] > bigone)
        bigone = numbers[i];

    i++;
}

This is the same loop but with for. Not sure why you are checking if there are 5 or less elements in the array but ok. This checks the length on every iteration.

for(var i = 0; numbers.length < 5 && i < numbers.length; i++)
{
    if(numbers[i] > bigone)
        bigone = numbers[i];
}

A better method to just check it once is to wrap the for loop in an if statement like this:

 if(numbers.length < 5)
 {
     for(var i = 0; i < numbers.length; i++)
     {
         if(numbers[i] > bigone)
             bigone = numbers[i];
     }
 }

Solution 2

I presume you are trying to find the largest number in the array. Another way to do this is to use the forEach method, which takes a callback function as an argument. The callback is executed once for each element of the array.

var numbers = [4, 12, 3, 5, 1]
var big  = 0;
numbers.forEach(function(number) { if(number > big) big = number; });
console.log(big); //Prints 12

More on Array.forEach

Share:
21,798
Dolbyover
Author by

Dolbyover

Updated on February 12, 2020

Comments

  • Dolbyover
    Dolbyover about 4 years

    I am trying to create a while loop in Javascript. I have a an array called numbers that contains 5 numbers. I also have a variable called bigone that is set to 0. I am trying to write a while loop that has an if statement that compares each value in the array to bigone. When the number in the array slot is greater then bigone, I want to assign that number to bigone. I cant figure it out. Here is what I have so far but it wont work. Yes this is homework and NO I am not asking for the answer, just for some guidance in the right direction. Here is as far as I have gotten :

    while ( numbers.length < 5 ) {
        if ( numbers > bigone ) {
        bigone = numbers
        }
      }
    

    Any ideas?

  • basarat
    basarat about 11 years
    best solution. However I would like to mention it is ES5 only, e.g. will not work in IE 8 and below.