//flex table opened by JP

Click to See Complete Forum and Search --> : Javascript Circular Array


CompGeek01
07-03-2005, 12:47 AM
Please someone give me insight into why the SHIFT RIGHT function doesn't work. It's pretty much the opposite of the left shift function....but it just doesn't work.

It's late, maybe it'll look different to me tomorrow.


function updateMe() {
box = document.getElementById("pictures");
box.innerHTML = '';
for (x=0; x<pictures.length; x++)
{
box.innerHTML += pictures[x];
}
}

function shiftLeft() {
box = document.getElementById("pictures");
var saveMe = pictures[0];
for(x=0; x<pictures.length-1; x++)
{
pictures[x] = pictures[x+1];
}
pictures[pictures.length-1] = saveMe;
updateMe();
}

function shiftRight() {
box = document.getElementById("pictures");
var goAway = pictures[pictures.length-1];
for(x=1; x<pictures.length; x++)
{
pictures[x] = pictures[x-1];
}
pictures[0] = goAway;
updateMe();
}

CompGeek01
07-03-2005, 02:04 PM
Arg, it's sooooooooooooooooooo strange. I must not know something about javascript.

ScaryBinary
07-03-2005, 04:44 PM
You're stepping through your array the wrong way. I'm finding it hard to describe the issue, so here's an example. Let's say you have a 4-element array that looks this:

(pic0, pic1, pic2, pic3)

Your shiftRight function saves the last element in goAway, so goAway = pic3. Looks good.

Then your for loop starts at element 1, which is pic1, and copies the previous element (pic0) into the current element. So after the first iteration (x=1) you have:

(pic0, pic0, pic2, pic3)

At the next iteration (x=2), again your loop copies the previous element into the current one, so you get:

(pic0, pic0, pic0, pic3)

:eek:

Your previous element will always be whatever your very first element was.

You need to step backwards through the array, like:for(x=pictures.length - 1; x>0; x--) {
pictures[x] = pictures[x-1];
}

Then overwrite element 0 with whatever your last element was (i.e, whatever you stored in goAway).

At least I think that's what the issue is! :D

CompGeek01
07-03-2005, 06:09 PM
I knew it was something logically! I always tend to overwrite existing array entries like this! Good thing it's nothing mission critical! Thanks SB.