【问题标题】:How can I generate a radom number for twice? [duplicate]如何生成两次随机数? [复制]
【发布时间】:2017-07-22 01:56:47
【问题描述】:

所以,伙计们,我正在尝试制作一个返回随机数的函数(我需要该代码以独占方式执行)为不同的两个函数生成相同的数字。基本上我将调用一个返回随机数的函数,但是当我再次调用该函数时,我需要它与前一个函数中的数字相同(我不太擅长 javascript。)。我有这些代码,但它当然会在每个函数中生成另一个数字:

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

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

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

【问题讨论】:

  • rand 设为全局变量并在chan 中分配给它,并在sell 中使用它(不分配给它)。

标签: javascript function random


【解决方案1】:

你必须改变你的逻辑才能得到你想要它做的事情。它违背了 rand 函数试图强制它返回相同值两次的目的。而不是这样,只需获取变量,然后将其传递给您需要的函数。示例:

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);
}

【讨论】:

  • 非常感谢您的即时答复和帮助:)
【解决方案2】:

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());

基本上每次调用 chan 时都会创建新的随机数,并在每次调用 sell 时返回该随机数。

【讨论】:

    【解决方案3】:

    基本上我会调用一个返回随机数的函数 但是当我再次调用该函数时,我需要它是相同的数字 和上一个函数一样

    你可以将Math.floor(Math.random() * 21) + 40的当前值存储为函数的一个属性,如果属性没有定义,返回属性值,将属性值存储为函数内的局部变量,否则将函数属性设置为@ 987654322@并返回局部变量

    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())
    }

    【讨论】:

      【解决方案4】:

      只需存储随机数,以便您可以重复使用它。

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

      【讨论】:

      • 为什么要投反对票? OP 说他不擅长 Javascript。有时事情可以用另一种方法来简化..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 2017-07-25
      • 2022-12-07
      • 2020-04-19
      相关资源
      最近更新 更多