循环中的随机数生成器语句每次都给我相同的数字. Java脚本 [英] A random number generator statement in a loop is giving me the same number every time. Javascript

查看:142
本文介绍了循环中的随机数生成器语句每次都给我相同的数字. Java脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写此循环,并且其中有一个随机数生成器.它为什么只为循环的所有迭代选择一个随机数,而不是一个新的随机数?这是我的代码:

So I am writing this loop, and I have a random number generator in it. How come it only picks one random number for all the iterations of the loop instead of a new random number? here's my code:

for ( i = 0; i < 25; i++ ) {
 var randNum = 0;
 var randNum = Math.floor(Math.random() * 5);
}

这是在chrome浏览器中.这段代码有什么问题吗?

this is in the chrome browser. Is there something wrong with this code?

推荐答案

您可能正在循环内的匿名函数内使用randNum变量.

You're probably using the randNum variable inside an anonymous function within the loop.

由于循环总是分配给相同的变量,因此在循环结束后对任何匿名函数的任何调用都只会看到最后一个数字.

Since the loop always assigns to the same variable, any calls to any of the anonymous functions after the loop finishes will see only the last number.

要解决此问题,请将循环的主体移至单独的函数(命名函数或匿名函数)中.

To fix this, move the body of the loop into a separate function (either named or anonymous).

这篇关于循环中的随机数生成器语句每次都给我相同的数字. Java脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆