Trip
Trip

Reputation: 27114

Why won't this loop produce my desired result?

Desired result :

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

My loop:

arr = []
n = 0; b = 0
while b < 2
  while n < 12
    arr.push n
    n++
  b++
return arr

Actual result :

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Upvotes: 2

Views: 88

Answers (1)

Ian
Ian

Reputation: 50905

Reinitialize the value of n to 0 after being done with it in the inner loop:

arr = []
n = 0; b = 0
while b < 2
  while n < 12
    arr.push n
    n++
  n = 0         // <------ Added this
  b++
return arr

That way, each outer iteration has a "fresh" value of n.

Although with this, I'm getting the values 0 to 11, not 1 to 12 as you think. So I would modify it to this (with real JS):

function test() {
    var arr = [];
    var n = 1;
    var b = 0;
    while (b < 2) {
        while (n <= 12) {
            arr.push(n);
            n++;
        }
        n = 1;
        b++;
    }
    return arr;
}

But as @Blender has pointed out, since you're really just emulating a for loop, use one!:

function test2() {
    var arr = [];
    for (var b = 0; b < 2; b++) {
        for (var n = 1; n <= 12; n++) {
            arr.push(n);
        }
    }
    return arr;
}

Upvotes: 6

Related Questions