Jump to content
Gilbert

if not working in for loops

Recommended Posts

I'm baffled by this - I am trying to master for loops and I seem to have run into a snag.  I looked up w3's nested for loops and got an example ( you can find it @ javascript statements and click on the 'for' link - at the bottom of the page) and it works great and I understand it .  Then I tried to inject an 'if' statement to interrupt it on a condition, but I got some unexpected results and I can't see what is wrong.  The logic seems correct - maybe someone can help me.   The 1st listing is directly from the example and in the second listing I injected a 2 line if statement - I got the results   I=o, j = 2 993 994   and there it stopped.   I also changed the values of i & j, but I don't see why that matters.   Thanks for any help!

<!DOCTYPE html>
<html>
<body>

<p>In this example, we have two loops. Because there is one loop that is inside the other, we call this a nested loop. The first loop is often called an "outer loop", and the second is often called the "inner loop" because it is inside the first, outer loop.</p>

<p>The outer loop executes first, and for each time the outer loop is executed, the inner loop will also execute.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var text = "";
    var i, j;

    for (i = 0; i < 3; i++) {
        text += "<br>" + "i = " + i + ", j = ";   

        for (j = 10; j < 15; j++) {
            document.getElementById("demo").innerHTML = text += j + " ";
        }
    }
}
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var text = "";
    var i, j;

    for (i = 0; i < 5; i++) {
        text += "<br>" + "i = " + i + ", j = ";   

        for (j = 2; j < 5; j++) {
            document.getElementById("demo").innerHTML = text += j + " ";
            if (i = j) {
            	text += 99;
            }
        }
    }
}
</script>

</body>
</html>

 

Share this post


Link to post
Share on other sites

if (i = j) {

That assigns the value of j to i, and then tests the value of i, it does not compare i and j to see if they're equal.  Check the page on operators to look at the different operators you can use.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...