Doubt random string with Javascript

Asked

Viewed 2,243 times

1

Personal I need to return 2 random strings 'John' or 'Mary' to implement in the following table.. I already did a Google search, but I could only return the WHOLE numbers and not the strings.. Thank you! Follows 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>';
}
  • Generates a number between 1 and 2. If give one is John, 2 is Mary.

  • Good alternative, I will test here...

  • If it becomes easier even or odd, you can check if any variable is even as follows. Suppose a number x, then x is even if (x % 2) == 0 or odd if (x % 2) == 1.

3 answers

2


Follows a alternative to randomly return the strings:

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

  • Thank you Brother, I managed to settle with your reply. grateful!

1

Call this function in "//here comes the logic of names".

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

1

A solution to N names, without needing to change 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 input of the item to be searched.

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

  • A bizarre problem is happening. When I run the first time, it works ok. If I run a second time, the snippet doesn’t work and redirects me to that page: https://stacksnippets.net/js.

  • @Renan also happened to me, I think it’s bug here on the site. I’ll wait to see if there are in more posts, and I launch the bug-report.

  • There are hours that returns undefined in the console.log. Odd not!?

  • @Renan the undefined was my mistake because I was generating too many numbers :) I corrected.

Browser other questions tagged

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