首页 > 解决方案 > 一旦应用于 var,Math.random 返回相同的数字

问题描述

Math.random似乎在控制台中工作正常。即使我申请Math.floor它,也没有问题。但是,一旦我将 a 分配var给代码。我只是得到相同的号码返回。我写的例子:

数学.随机();<0.2650735060984091

数学.随机();<0.23735521448696772

数学.随机();<0.690841980599159

Math.floor(Math.random() * 10); <8

Math.floor(Math.random() * 10); <7

Math.floor(Math.random() * 10); <1

var x = Math.floor(Math.random() * 10);

<未定义

X; <4

x <4

x <4

x <4

当我分配 any 时,输出始终为 4 var

我怎么解决这个问题?

标签: javascript

解决方案


您正在做的是存储Math.floor(Math.random() * 10);in的值x。不是Math.floor(Math.random() * 10);每次您使用 x 时都会调用它。这是相同的值。要实现这一点,您需要有一个函数,以便您Math.floor(Math.random() * 10);每次都可以调用。

function randomFloor() {
 return Math.floor(Math.random() * 10)
}

console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)


推荐阅读