How do you save the output of a random number generator function to be recalled in a different function?
For example, in the code below, I would be using the function randNum()
to roll the dice and return
the value of w
to the saveDiceNumber()
function as a variable.
Then I would save the first value received from the randNum()
function into the new variable x
located in the saveDiceNumber()
function. Then I would like to repeat the process for variables y
and z
, without losing the newly created value of x
.
So in essence, I would like to create a single function that uses the same random number generator to create 3 different variables and then recall the value of those variables without having to re-generate/re-roll random numbers.
The random number generator function:
function randNum(){
return Math.floor(Math.random()*6);
}
Function where RNG output should be saved:
function saveDiceNumber(){
var w = randNum(); //roll the dice for the first permanent value
var x = randNum(); //second output of dice
var y = randNum(); //third output of dice
var z = randNum(); //forth output of dice
pickFruit(x);
}
Where the output of saveDiceNumber()
will be used:
function pickFruit(letter){
switch(letter){
case(1):
console.log("Apples");
break;
case(2):
console.log("Pears");
break;
case(3):
console.log("Bananas");
break;
case(4):
console.log("Mangos");
break;
case(5):
console.log("Pineapples");
break;
case(6):
console.log("Avacados");
break;
}
Typing: saveDiceNumber()
will console log different fruit every time, even though the function pickFruit(x)
is the same.
I need the value of the variable x
to permanently equal to =
the value generated by one usage of the randNum()
function.
So if I roll a 3, then x
needs to be permanently equal to 3.