Generation of random numbers – Math.random()

huangapple go评论58阅读模式
英文:

Generation of random numbers - Math.random()

问题

以下是翻译好的部分:

"我前几天尝试生成一个随机数。任务基本上是这样的,给定一个包含名称的数组,我将随机在控制台上记录名称。我尝试生成一个随机数,它将作为元素的索引来访问名称(例如,array[random_number_as_index])。

当我将Math.random()方法存储在一个变量中并访问同一个变量时,结果一遍又一遍地相同。我的代码行看起来是这样的。

const randomNumber = Math.floor(Math.random()*10));

而当它作为函数的一部分时,例如,

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

每次调用该函数时实际上会生成一个随机数。我期望的是,访问变量时,每次都会生成一个随机数,但事实并非如此,只有当它在函数内部时才起作用。"

英文:

I was working trying to generate a random number the other day. The assignment is basically that, given an array with names, I was gonna log names on the console at random. I tried to generate a random number that is gonna help accessing the names working as the index of the elements (e.g., array[random_number_as_index]).

My confusion started when storing the method Math.random() in a variable and accessing that same variable, the result was the exact same number over and over. My line of code looks something like this.

const randomNumber = Math.floor(Math.random()*10));

Whereas when part of a function, e.g.,

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

would actually generate a random number every time the function is invoked. My expectation was that, upon accessing the variable, a random number was gonna be generated every single time, which was not the case, and only works if it is within a function.

答案1

得分: 1

生成一个随机数然后将该随机数分配给`randomNumber`

`randomNumber`是一个常量变量意味着其值不能在后续更改)。

你正在生成一个随机数然后将其保存在一个变量中

```js
function randomNum() {return Math.floor(Math.random()*10));}

定义一个函数,当调用时返回一个随机数。

每次调用randomNum都会生成一个新的随机数。


<details>
<summary>英文:</summary>

```js
const randomNumber = Math.floor(Math.random()*10));

Generates a random number, then assigns that random number to randomNumber.

randomNumber is a constant variable (meaning its value cannot be changed after the fact).

You're generating one random number, then saving it in a variable.

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

Defines a function that returns a random number when called.

Each invocation of randomNum generates a new random number.

huangapple
  • 本文由 发表于 2023年2月6日 02:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定