开发者

JavaScript Beginner Question (Loops)

开发者 https://www.devze.com 2023-02-21 09:05 出处:网络
Today is my first day in JavaScript. The开发者_如何学Python book (JavaScript Definitive Guide) has an excersice printing all the factorials.

Today is my first day in JavaScript. The开发者_如何学Python book (JavaScript Definitive Guide) has an excersice printing all the factorials.

This is what I did:

<html>
<b><head> Factorial - JavaScript - Ex1</head></b>
<body>
        <h2> Factorials List </h2>
<script>

        var fact = 1; 
        var num = 1;
        for(num <= 10; num++)
            {
                fact=fact*num;
                document.write(num + "! = " + fact + "<br>");

            }
</script>
</body>
</html>

There is a problem which I don't exactly know. I checked the book and the way that writer solved it was by initializing the variable num inside the loop FOR. I did that and it worked. But what is the difference between that and mine?

Enlighten me Experts :)


A for loop's syntax must be

for (<initializer>; <condition>; <increment>) {
    <body>
}

While any of <initializer>, <condition> and <increment> can be omitted, none of the semicolons ; can be removed. That means, your for loop must be written with an extra semicolon:

var num = 1;
for(; num <= 10; num++)
//  ^

Or just move the var num = 1; into the for, which is normally what people would do:

for (var num = 1; num <= 10; num ++) 
//   ^^^^^^^^^^^^
0

精彩评论

暂无评论...
验证码 换一张
取 消