I'm just learning JavaScript and I'm trying to have an if else statement declare something, but I want to use a loop with it. Basically something like this:
var myNum = 1;
var linebreak = "<br />开发者_高级运维";
var d3d = "You're very lucky! ^_^";
var p3p = "<p>Too Bad. Maybe Next Time.</p>";
for (myNum = 0; myNum < 7; myNum++) {
if (myNum == 7) {
document.write(myNum + linebreak + d3d + myNum);
} else {
document.write(p3p + "You're not very lucky today...");
};
}
It would say You're not very lucky for the first 6 loops, but at the 7th loop it would say you're very lucky. I know something is wrong, because if it was written correctly, then at the end of the loop it would write the if statement. I know you'd usually have the for loop variable set as "i", but I also need the if else statement to be able to know what that is. Does anyone know what I'm doing wrong?
Your loop never actually reaches 7 because your condition is to continue if myNum
is below 7. To keep it at seven iterations and do what you want, you'd have to check to see if (myNum == 6)
. On a side note, to understand loops better, you can try running this code:
for(var i = 0; i < 5; i++)
alert(i);
for(var i = 0; i <= 5; i++)
alert(i);
精彩评论