samedi 4 novembre 2017

Have a var return a specific value based on an if statement

I have written a for loop to sing 99 Bottles of Beer on the Wall. I am using an if statement to return a specific value to var word. When the number of bottles is 99 to 2 then var word="bottles" and when the number of bottles is 1 then var word = "bottle". This works fine but in the final line of the final iteration when the number of bottles is 0 and I expect var word to equal "bottles", it is still coming up as "bottle".

var word="bottles";
for (var count = 99; count > 0; count-- ) { 
   document.write(count + " " + word + " of beer on the wall, <br>");
    document.write(count + " " + word + " of beer.<br>" );
    document.write("Take one down, pass it around,<br>");
    var count2 = count - 1;
        if (count2 === 1) {
        word = "bottle";
        }
    document.write(count2 + " " + word + " of beer on the wall.<br><br>");
    }   

Is the condition of my if statement incorrect? This is what the final three iterations look like in the browser:

3 bottles of beer on the wall, 3 bottles of beer. Take one down, pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer. Take one down, pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer. Take one down, pass it around, 0 bottle of beer on the wall.

Aucun commentaire:

Enregistrer un commentaire