Jump to content

Basic Else...if Question


billydocks

Recommended Posts

Hi all.New to javascript so this is a pretty basic question. I have gone through the W3C tute and another tutorial online (which I based my example off, just for something to learn/practice on).

var drink = "beer";var lyrics = "";var cans = 10;while (cans > 0) { lyrics = lyrics + cans + " cans of " + drink + " on the wall <br>"; lyrics = lyrics + cans + " cans of " + drink + "<br>"; lyrics = lyrics + "take one down, pass it around,<br>"; if (cans > 1) { lyrics = lyrics + (cans-1) + " cans of " + drink + " on the wall <br><br>";}else { lyrics = lyrics + "no more cans of " + drink + " on the wall <br>";}cans = cans - 1;}document.write(lyrics);
Apologies for pasting the whole lot in there, but I am not sure how else to be clear with my question, which is this:How can I change the 'cans' plural to be just 'can' when the amount of cans reaches 1? If I insert a if (can == 1) in there, the condition is met and the script does not run on to the else { section to reveal there are no more cans of beer on the wall. I hope this question makes sense. I am fairly certain it should be an easy fix, but I've tried re-reading through the W3C tutorial without finding a clue (or perhaps more to the point, not recognising a possible solution).Thanks for the help!bd
Link to comment
Share on other sites

in javascript you can do else if's like so:

if (cans > 1) {//}else if (cans == 1) {//}else {//}

although for the 's' on the end of can, i'd rather have it in a ternary statement like:

lyrics = lyrics + cans + " can" + (cans != 1 ? 's' : '') + " of " + drink + " on the wall <br>";

where this part:

(cans != 1 ? 's' : '')

means to include an 's' in the string if the cans variable isn't 1, otherwise if it is 1 then just include a blank string '' (which won't add any characters to the string)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...