How to push data in an empty array every time a function is triggered

0

I am trying to save a random value in an array every time a user clicks on a button but the value only remains in it at the time of execution of the function.

let boton = document.getElementById('boton');
boton.addEventListener("click", iniciar);

let numeroRandom = Math.floor((Math.random() * 4) + 1);

let secuencia = [];

function iniciarluz(valor){

  let elementos = document.getElementsByTagName('li');
  elementos[valor-1].className = "prendida";
  secuencia.push(valor);
}

function iniciar(){
  iniciarluz(numeroRandom);
}
    
asked by FerAdamo 25.10.2018 в 14:59
source

1 answer

1

You have to put the random number inside the function. The way you have it, you assign it only once.

let boton = document.getElementById('boton');
boton.addEventListener("click", iniciar);

let secuencia = [];

function iniciarluz(valor){

let elementos = document.getElementsByTagName('li');
elementos[valor-1].className = "prendida";
secuencia.push(valor);
console.log(valor);
}

function iniciar(){
let numeroRandom = Math.floor((Math.random() * 4) + 1);
iniciarluz(numeroRandom);
}
.prendida {
  color: green;
}
<button id="boton">Boton</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
    
answered by 25.10.2018 в 16:43