Gilbert Posted March 21, 2018 Share Posted March 21, 2018 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> Link to comment Share on other sites More sharing options...
justsomeguy Posted March 21, 2018 Share Posted March 21, 2018 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. Link to comment Share on other sites More sharing options...
Gilbert Posted March 21, 2018 Author Share Posted March 21, 2018 Stupid, stupid, stupid!! Thanx, Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now