phantom phantom - 21 days ago 10
Javascript Question

Switch from increment to decrement when reach the end of an array

I am looping through an array. when

current===arr.length
I want to decrement
current
again. Then, when
current === 0
I want to increment
current
again.

Below is the code I have. does my question make sense? i cannot figure out the logic in my head.

var arr = [1,2,3,4],
current = 0;

$('body').click(function(){
console.log(arr[current]);
current++;
if(current === (arr.length -1)){
current--;
}
});

Answer

It's not super pretty, but it's what I came up with quickly:

var arr = [1,2,3,4],
    current = 0,
    dir = "up";

$('body').click(function(){
    if(current === arr.length - 1){
        dir = "down";
    } else if(current === 0){
        dir = "up";
    }

    switch(dir) {
        case "up":
           current++;
           break;
        case "down":
           current--;
           break;
    }

    console.log(arr[current]);
});