所以,我正在尝试创建一个函数,返回一个随机数(我需要代码才能被执行),为不同的两个函数生成相同的数字。基本上我将调用一个返回随机数的函数,但是当我再次调用该函数时,我需要它与前一个函数中的数字相同(我不是很擅长javascript。)。我有这些代码,但当然它会在每个函数中生成另一个数字:
function gen() {
return Math.floor(Math.random() * 21) + 40;
}
function chan() {
var rand = gen();
}
function sell() {
var rand = gen();
}
答案 0 :(得分:3)
你必须改变你的逻辑才能得到你想要的东西。它违背了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);
}
答案 1 :(得分: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());
每次调用chan时基本上都会创建新的随机数,并且每次调用时都会返回该随机数。
答案 2 :(得分:0)
基本上我打算调用一个返回随机数的函数 但是当我再次调用该函数时,我需要它是相同的数字 与前一个函数一样
如果未定义属性,可以将Math.floor(Math.random() * 21) + 40
的当前值存储为函数的属性,返回属性值,将属性值存储为函数中的局部变量,否则设置函数属性到undefined
并返回局部变量
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())
}
答案 3 :(得分:-1)
只需存储随机数,以便您可以重复使用它。
var rand;
function gen() {
return Math.floor(Math.random() * 21) + 40;
}
function chan() {
rand = gen();
}
chan();
console.log(rand);