mardi 21 avril 2020

Iterating random number within For loop

I'm attempting to use a For loop to add a random integer (from 0-2) to a variable a specified amount of times. The problem I'm having is that the loop isn't using a new random number every time it loops, so I'm only getting either 0, 9, or 18 if I pass in 9 for example.

I am expecting an object to return with keys "a" and "b" having different number values.

Here's my random number getter:

function randomNumber(min, max){
   min = Math.ceil(0);
   max = Math.floor(3);
   return Math.floor(Math.random() * (max - min)) + min;
}

and here's the function where I call randomNumber():

function objMaker(cb, num){
  let obj = {
    a: 0,
    b: 0
  }
  for (var i = 0; i < num; i++) {
    obj.a += cb;
    obj.b += cb;
  }
  return obj;
}

objMaker(randomNumber(), 9)
// returns obj { a:0, b:0}
// or obj { a:9, b:9}
// or obj { a:18, b:18}

I'm a beginner so I appreciate the help as I have not been able to find anything on the matter. Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire