Results 1 to 7 of 7

Thread: Tutorial: For Loops in JavaScript

  1. #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

    Great, now even Kirupa is { facebooking | twittering }

  2. #2
    You can also iterate the properties of an object using the for loop:

    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
    }
    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 arr = ['1', '2', '3'];
    for (var i in arr) {
        alert(i); // Outputs 0, 1, 2
        alert(arr[i]); // Outputs '1', '2', '3'
    }
    You can easily mess it up with the Array object is modified:

    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()
    }
    Great tutorial as always Kirupa.

  3. #3
    I'd think that the for..in loop would be a separate tutorial.

  4. #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

    Great, now even Kirupa is { facebooking | twittering }

  5. #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 nested
    AS2 / AS3 / JS / JQUERY / (X)HTML / HTML5 / CSS / CSS3 / PHP

  6. #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?

    Great, now even Kirupa is { facebooking | twittering }

  7. #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

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012