Doubt random string with Javascript

1

I need to return 2 random strings 'John' or 'Mary' to implement in the following table .. I already ran a Google search, but I could only return the integers, not the strings. Thank you! Follow the code ...

for(i = 1; i<=30; i++) {
var maximo = 5;
var a = parseInt(Math.random()*maximo+1);
var b = parseInt(Math.random()*maximo+1);
var name = // <= aqui vem a logica dos nomes!

table += '<tr><td>'+i+'</td>';
table += '<td>'+a+'</td>';
table += '<td>'+b+'</td>';
table += '<td>'+name+'</td>';
table += '<td>1</td>';
table += '<td>1</td>';
table += '<td>1</td></tr>';
}
    
asked by anonymous 11.07.2017 / 16:35

3 answers

2

Follow an alternative to randomly return strings:

function MariaOuJoao(){
  var opcoes = ["Joao","Maria"];
  alert(opcoes[Math.random() < 0.5 ? 0 : 1]);
}
<button onclick="MariaOuJoao()">Random</button>
    
11.07.2017 / 16:41
1

Call this function in "// here comes the name logic".

function pegaUmQualquer() {
    min = Math.ceil(0);
    max = Math.floor(1);
    return Math.floor(Math.random() * (max - min + 1)) + min === 0 ? "João" : "Maria";
}
    
11.07.2017 / 16:41
1

A solution for N names, without needing to change any more in the code.

Create an array with the names you want to use and then use Math.ceil(Math.random() * (nomes.length - 1)) as the index of the search element.

var nomes = ['João', 'Maria', 'Antonio', 'Joana'];
var name = nomes[Math.ceil(Math.random() * (nomes.length - 1))];
console.log(name);
    
11.07.2017 / 16:42