jeudi 24 septembre 2015

Can the IF statement be used instead of WHILE loop in this script?

I'm learning JavaScript with the help of a number of books. In one of them I came up with a script that displays a couple of flags and then you click on them to randomly change them:

var myImages = new Array("usa.gif","canada.gif","jamaica.gif","mexico.gif");

function changeImg(that) {
        var newImgNumber = Math.round(Math.random() * 3);

        while (that.src.indexOf(myImages[newImgNumber]) != -1)
        {
            newImgNumber = Math.round(Math.random() * 3);
        }

        that.src = myImages[newImgNumber];
        return false;
}

It has a while loop to make sure that when you click on a flag you don't end up with the same one. The rest of the code in HTML looks like this:

<body>
    <img name="img0" src="usa.gif" border="0" onclick="return changeImg(this)" />
    <img name="img1" src="mexico.gif" border="0" onclick="return changeImg(this)" />
</body>

Now, my question is, if I use an IF statement instead of a while loop, apparently the code works the same. In this particular example why is the while loop used instead of IF? Thanks.

Aucun commentaire:

Enregistrer un commentaire