Result of iteration of array in a variable

-1

Hi, what I want is to get a random value stored in a variable after iterating a loop array 10 times.

The code that I've made just throws me a letter.

If anyone can give me a hand with this, I would be grateful.

Greetings.

var palos = ["Trebol","Picas","Corazon","Diamantes"];
var combi=[];
for(var i = 0; i<palos.length; i++){
   for(var j=1; j<=10; j++){ 
       combi = combi + (" - Carta: "+j+" de "+palos[i]);
   }
}
var random = combi[Math.floor(Math.random() + combi.length)]
console.log(random)
    
asked by atallpa 21.08.2018 в 13:43
source

2 answers

2

You have the error when creating the array of letters in:

combi = combi + (" - Carta: "+j+" de "+palos[i]) 

You are concatenating a string. Then combi becomes a string with all the letters concatenated. To create the array you have to add:

 combi.push( " - Carta: "+j+" de "+palos[i]);

This creates you the array with all the cards.

Then to get a random number you have multiplied the random with the maximum you want the random:

Math.floor(Math.random() * combi.length)

This would give you a random number between 0 and the number of cards combi has.

Altogether, you get:

var palos = ["Trebol","Picas","Corazon","Diamantes"];
var combi=[];
for(var i = 0; i<palos.length; i++){
   for(var j=1; j<=10; j++){ 
       combi.push( " - Carta: "+j+" de "+palos[i]);
   }
}

var random = combi[Math.floor(Math.random() *combi.length)]
console.log(random)
    
answered by 21.08.2018 в 13:58
1

I just want to add that as it seems that the problem is raised, it would not be necessary to create the second array:

var palos = ["Trebol","Picas","Corazon","Diamantes"];


var randomPalos = Math.floor(Math.random()*palos.length);  

var randomNumero = Math.floor(Math.random() * 10) + 1;



console.log( " - Carta: "+randomNumero+" de "+palos[randomPalos]);
    
answered by 21.08.2018 в 14:18