英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论