How to save a value entered in a prompt in a variable by means of a loop

1

How would it be to save the value 0 entered in prompt in variable value and so on the others? Thanks

let valor, valor1; valor2, valor3;

	for (var i = 0; i < 3; i++) {

		let prompt('Introduce un valor para guardarlo en una variable');
		
		valor = i;
		valor1 = i;
		valor2 = i;
		valor3 = i;
		console.log(valor);

	}
    
asked by francisco dwq 08.03.2018 в 17:07
source

2 answers

1

You can create an array valor=[] , and when you scroll the for go keep the values of i in valor[] . Then a new for to show it. I hope I have been helpful.

Code:

let valor = [];

   for (var i = 0; i < 3; i++) 
   {
       valor[i] = prompt('Introduce un valor para guardarlo en una variable: ');
   }

   for (var i = 0; i < 3; i++) 
   {
       console.log(valor[i]+" ");
   }
    
answered by 08.03.2018 в 17:21
0

You can save your values in an array where you will put the values that are entered in the prompt. If what you want is to have access to a variable that you already define, you can use the expression eval () that would dynamically execute the assignment expression of your value. Together, both solutions in the same example.

<button type="button" onclick="ShowPrompt()">Ingresa Numeros</button>
<script>
  var list = []; //array de valores
  let valor0, valor1, valor2; //tus valores declarados

  function ShowPrompt() {
    for (var i = 0; i < 3; i++) {
      var valor = prompt("Introduce el valor " + (parseInt(i) + 1) + " para guardarlo");
      
      eval(" valor" + i + " =" + valor); // aqui asignas el valor a tu varaible de forma dinamica
      list[i] = valor; // aqui guardas el valor en el array definido
      
      console.log(valor);
    }
  }
</script>
    
answered by 08.03.2018 в 17:37