[英]How would I get it where every time it generates a random number it adds it onto a variable in javascript?
How would I make it where every time it generates a random number it adds it on to a variable called Num my code is below. 我将如何在每次生成随机数时将其添加到以下代码中称为Num的变量中。
function Generate() {
var Num;
var RanN = Math.floor((Math.random()*10)+1);
for (var i=0;i<4;i++) {
Num += RanN;
}
}
If you're trying to generate a random number i
amount of times and add it to a pre-existing number, you'll want something like this: 如果您尝试生成一个随机数i
次,然后将其添加到预先存在的数字中,则需要这样的代码:
function Generate(startNum, iterations) {
for (var i=0; i<iterations; i++) {
startNum += Math.floor((Math.random()*10)+1);
}
return startNum;
}
And you would use it like this (if you want to add ten randomly generated numbers): 您可以像这样使用它(如果您想添加十个随机生成的数字):
var num = 0;
num = Generate(num, 10);
Here is what I think the OP want: 这是我认为OP想要的:
function Generate(Num) {
for (var i=0;i<4;i++) {
Num += Math.floor((Math.random()*10)+1);
}
return Num;
}
The answers are slightly different in structure to your function. 答案在结构上与您的功能略有不同。 If you want to fix what you have (seeing that you have moved the random function into the loop), just change var Num;
如果您想解决现有问题(看到您已将随机函数移入循环),只需更改var Num;
to var Num=0;
到var Num=0;
, which will fix the NaN error (because you can't add a number to something that is not defined, because it is Not a Number) ,它将解决NaN错误(因为您不能将数字添加到未定义的内容中,因为它不是数字)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.