JavaScript - Execute Data from an array always in the same order

3

Good / Good Day / Afternoon / Evening, I would like JavaScript help, how do I execute data from an array in the same order, for example:

var teste = ["valor1", "valor2"];
document.getElementById("id").innerHTML = 

As I do when I click a button the value of the text is the value one, then when I click again it is the value two, and then restart. Thank you, sorry for the huge question;)

    
asked by anonymous 03.07.2016 / 22:59

1 answer

2

You need to create a variable that stores the information of which element of the array was shown. An index flag. And then every time you click on the element you increase that value variable.

An example would look like this:

var arr = ['Olá', 'hoje', 'esteve', 'um', 'lindo', 'dia!'];
var index = 0;
var btn = document.querySelector('button');
var div = document.querySelector('div');

btn.addEventListener('click', function() {
    div.innerHTML = arr[index];
    index++;
    if (index == arr.length) index = 0;
});

jsFiddle: link

    
03.07.2016 / 23:08