Javascript - Run Data from an array always in the same order

Asked

Viewed 36 times

3

Good/Good Morning/Afternoon/Evening, I would like a Javascript help, how do I run data from an array always in the same order, example:

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

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

1 answer

2


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

An example would be 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: https://jsfiddle.net/r8d787d8/

  • 1

    Thank you very much again!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.