1

So guys I am trying to make a function that returns a random number (which I need that code to be executed excluesively) generate the same number for different two functions. Basically I am going to call a function that returns a random number but when I call that function again, I need it to be the same number as in the previous function (I am not very good at javascript.). I have these codes, but of course it generates some another number in each function:

function gen() {
    return Math.floor(Math.random() * 21) + 40;
}

function chan() {
    var rand = gen();
}

function sell() {
    var rand = gen();
}
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73

4 Answers4

3

You'll have to change your logic to get what you want it to do. It defeats the purpose of the rand function to try to force it to return the same value twice. Rather than that, just get the variable, and then pass it into the functions you need. Example:

function gen() {
  return Math.floor(Math.random() * 21) + 40;
}

function chan(randomNumber) {
 //logic goes here
}

function sell(randomNumber) {
  //logic goes here
}

function app() {
  var randomNumber = gen();
  chan(randomNumber);
  sell(randomNumber);
}
Eric Hoose
  • 101
  • 5
0

var rand;
function gen() {
    return Math.floor(Math.random() * 21) + 40;
}

function chan() {
    rand = gen();
    return rand;
}

function sell() {
    return rand;
}

console.log(chan());
console.log(sell());

Basically create new random number everytime chan is called, and return that random number everytime sell is called.

almost a beginner
  • 1,622
  • 2
  • 20
  • 41
0

Basically I am going to call a function that returns a random number but when I call that function again, I need it to be the same number as in the previous function

You can store the current value of Math.floor(Math.random() * 21) + 40 as a property of the function if the property is not defined, return the property value, store the property value as a local variable within the function, else set the function property to undefined and return the local variable

function gen() {
  if (!this.n) {
    this.n = Math.floor(Math.random() * 21) + 40;
    return this.n;
  }
  if (this.n) {
    const curr = this.n;
    this.n = void 0;
    return curr
  }
}

for (let i = 0; i < 10; i++) {
  console.log(gen())
}
guest271314
  • 1
  • 15
  • 104
  • 177
-1

Just store the random number so that you can reuse it.

var rand;
function gen() {
return Math.floor(Math.random() * 21) + 40;
}

function chan() {
 rand = gen();
}

chan();
console.log(rand);
Charlie Ng
  • 640
  • 5
  • 11
  • why down vote? OP said he is not good at Javascript. Sometimes things can be simplified with another approach.. – Charlie Ng Jul 22 '17 at 02:08