PDA

View Full Version : Array Loop Logic Problem


thepeskykid
05-15-2003, 10:57 AM
Hello,

This section of code is giving me problems

// tempArray2 = [[2,5],[0,10],[3,10],[1,12],[4,18]];

// loop through tempArray2 and assign n to mainArray[n][5]
var n = 0;
for (i=0;i<tempArray2.length;i++)
{
if (tempArray2[i][0] == n)
{
mainArray[n][5] = n;
i = 0;
n++;
}
}

I have stepped through it manually and got the following

n=0
i=0
i=1
mainArray[0][5]=0
i=0
n=1
i=1
i=2
i=3
mainArray[1][5]=1
i=0
n=2
mainArray[2][5]=2
i=0
n=3
i=1
i=2
mainArray[3][5]=3
i=0
n=4
i=1
i=2
i=3
i=4
mainArray[4][5]=4
i=0
n=5
i=1
i=2
i=3
i=4
end loop

when I run the code, mainArray[n][5] is correctly updated on the first and second passes only - for some reason all subsequent passes either insert a 0 or do not insert anything (mainArray[n][5] is initialised as 0)

I must be missing something here as I have stepped through it manually three times and it works but the 'live' code doesn't produce the same successfull result

Any help or clarification would be great

Thank you

:)

Weirdan
05-15-2003, 12:24 PM
var n = 0;
for (i=0;i<tempArray2.length;i++)
{
if (tempArray2[i][0] == n)
{
mainArray[n][5] = n;
i = -1;
n++;
}
}

i++ is executed after each iteration. So, if you want to restart loop, you have to set i to -1

thepeskykid
05-15-2003, 12:36 PM
thank you

:)