Results 1 to 7 of 7
-
April 15th, 2012, 06:26 PM #1
Tutorial: For Loops in JavaScript
Hi everyone,
This is the happening place to discuss all things related to the For Loops in JavaScript tutorial. If you want to be cool, you know you want to read it.
Cheers,
Kirupa
-
April 15th, 2012, 11:12 PM #2
You can also iterate the properties of an object using the for loop:
Gotta be careful with that one though because Arrays are objects in JS it's tempting to use that to iterate through an array. While it might look like it works at first:Code:var obj = { one: 1, two: 2, three: 3 } for (var property in obj) { alert(property); // Outputs 'one', 'two', 'three' alert(obj[property]); // Outputs 1, 2, 3 }
You can easily mess it up with the Array object is modified:Code:var arr = ['1', '2', '3']; for (var i in arr) { alert(i); // Outputs 0, 1, 2 alert(arr[i]); // Outputs '1', '2', '3' }
Great tutorial as always Kirupa.Code:Array.prototype.myCustomFn = function(){ // Does something }; var arr = ['1', '2', '3']; for (var i in arr) { alert(i); // Outputs 0, 1, 2, 3 alert(arr[i]); // Outputs '1', '2', '3', function() }
-
April 15th, 2012, 11:19 PM #3
I'd think that the for..in loop would be a separate tutorial.
-
April 16th, 2012, 10:41 AM #4
Yep, the for...in loop will be a separate one. I didn't want to muddy the waters too much with it in this tutorial
-
April 17th, 2012, 04:27 PM #5
Some things that might be good to mention:
- break and continue
- a for loop nested within another for loop
- breaking or continuing an outer loop when nestedAS2 / AS3 / JS / JQUERY / (X)HTML / HTML5 / CSS / CSS3 / PHP
-
April 17th, 2012, 07:41 PM #6
That's good feedback Swooter. I'll modify the tutorial to address all three of them. For the third point (breaking or continuing an outer loop when nested), is there anything special that I would need to do besides just breaking the inner loop?
-
April 19th, 2012, 02:44 PM #7
Hi Kirupa,
You can actually name your loops and break or continue it using that name:
Code:myloop: for ( var i = 0; i < 10; i ++ ) { for ( var j = 0; j < 10; j++ ) { if ( j == 5 ) { break myloop; } } }AS2 / AS3 / JS / JQUERY / (X)HTML / HTML5 / CSS / CSS3 / PHP

Reply With Quote

Bookmarks