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