Moustafa Jazzar
Moustafa Jazzar

Reputation: 63

loop through array forward and backward one at time?

This is my first question and I hope to find an answer here. I have an array

var arr = ['red', 'blue', 'black', 'green'];

I want to loop through it so I can console.log(); an element every time I click a btn and keep tracking the index so I can iterate backward if I clicked a different btn.

nextBtn.addEventListener('click',nextItem)

prevBtn.addEventListener('click',prevItem)

Thanks

Upvotes: 0

Views: 1441

Answers (2)

Carl Edwards
Carl Edwards

Reputation: 14434

In each function you'd grab the current index of the element in the array by increment/deincrementing a global variable that keeps track of where you currently are. To prevent going over/under the array you'd provide a conditional in each.

var arr = ['red', 'blue', 'black', 'green'];
var currentIndex = 0;

var nextBtn = document.getElementById('nextBtn');
var prevBtn = document.getElementById('prevBtn');

nextBtn.addEventListener('click', nextItem);

prevBtn.addEventListener('click', prevItem);

function nextItem() {
  if (currentIndex === (arr.length - 1)) {
    return;
  }
  
  console.log(
    arr[++currentIndex]
  );
}

function prevItem() {
  if (currentIndex === 0) {
    return;
  }
  
  console.log(
    arr[--currentIndex]
  );
}
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You could take a closure over the index and return an object with the function for getting the next or previous value of the array.

var array = ['red', 'blue', 'black', 'green'],
    index = function (i) {
        var out = document.getElementById('out');

        out.innerHTML = array[i];
        return {
            prev: function () {
                i && i--;
                out.innerHTML = array[i];
            },
            next: function () {
                i + 1 < array.length && i++;
                out.innerHTML = array[i];
            }
        }    
    }(0);

document.getElementById('nextBtn').addEventListener('click', index.next);
document.getElementById('prevBtn').addEventListener('click', index.prev);
<button id="prevBtn">prev</button> <span id="out"></span> <button id="nextBtn">next</button>

Upvotes: 2

Related Questions