0

I have two variables and I would like to add them randomly in a function, I do with math.random but the problem is that the value is sometimes the same, while I would like it to play between them two values, if it gives the first then the next time it will be the second and vice versa ... I hope I explained it well. Thank you.

     const btn = document.getElementById('button')
     function random(){
            var variable = 2
            var arr = [];
            var tabprenom=new Array('prenom 1','prenom 2')
            while(arr.length < 2){
              var r = Math.floor(Math.random() * variable-1) + 1;
              if(arr.indexOf(r) === -1) arr.push(r);
            }
    
            console.log(tabprenom[r]);
        }
        btn.addEventListener('click',random)
<button id="button"> Generer aleatoire unique </button> 
Reporter
  • 3,897
  • 5
  • 33
  • 47
student
  • 3
  • 4
  • Does this answer your question? [How to create a GUID / UUID](https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid) – Reporter Aug 11 '21 at 13:26
  • Can you please be more clear, so we can understand what you really want? – Adil Bimzagh Aug 11 '21 at 13:28
  • You don't need to randomize if you want to play between only 2 options – firatozcevahir Aug 11 '21 at 13:30
  • How can you alternate between two values and still be random? Won't the sequence always be 1 2 1 2 1 2 1 2? I mean I suppose it could either *start* with a 1 or a 2, but then, if you don't want to repeat, you're always going to get the other number next. Or do I misunderstand? To alternate between 1 and 2, you can get the next number with `x = (1 + 2) - x`. – Wyck Aug 11 '21 at 13:31
  • If you want a fixed or predictable order then you shouldn't use random. Or perhaps only start with a random value, then from there go through the sequence that you have in mind. – Peter B Aug 11 '21 at 13:32
  • This question needs to be edited to show some examples of the expected results. – Wyck Aug 11 '21 at 13:34

1 Answers1

0

If you want to play with only 2 values, you can do the following instead of randomizing.

const btn = document.getElementById('button')
let option = 0;

function random() {
  var tabprenom = new Array('prenom 1', 'prenom 2');

  console.log(tabprenom[option]);
  option = option ? 0 : 1;
}

btn.addEventListener('click', random);
<button id="button"> Generer aleatoire unique </button>
firatozcevahir
  • 892
  • 4
  • 13