Monday, May 20, 2024
83
rated 0 times [  84] [ 1]  / answers: 1 / hits: 25534  / 11 Years ago, fri, april 26, 2013, 12:00:00

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?


More From » if-statement

 Answers
6

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];
}
}

[#78611] Thursday, April 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynneg

Total Points: 205
Total Questions: 111
Total Answers: 112

Location: Djibouti
Member since Wed, Dec 8, 2021
3 Years ago
;