简体   繁体   English

JavaScript输出6个随机数

[英]JavaScript for output 6 random numbers

I'd like my output has 6 random numbers but my code only displays 4 numbers, and the numbers are the same. 我希望我的输出有6个随机数,但是我的代码仅显示4个数字,并且这些数字是相同的。

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

for(var i=0; i<7; i++){
    document.write(x + "</br>");
    i++;
}

Could someone please help? 有人可以帮忙吗?

You need to move .random() inside your loop. 您需要在循环中移动.random() Also, remove i++ from your loop, because that is already done by for() . 另外,从循环中删除i++ ,因为那已经由for()

Demo: 演示: jsFiddle

Script: 脚本:

for( var i=0; i<6; i++ ){
    var x = Math.floor(Math.random()*41);
    document.write(x + "</br>");
}

You don't need the i++ inside the form, it's 6 not 7 and you need to calculate the random numbers inside the for loop. 您不需要表格中的i ++,它是6而不是7,并且您需要计算for循环内的随机数。

for(var i=0; i<6; i++){
    var x = Math.floor(Math.random()*41);
    document.write(x + "</br>");
}

Why are you incrementing i twice? 你为什么增加i两次? Also, if all the numbers are going to be random, you need to execute the Math function inside of the loop. 另外,如果所有数字都是随机的,则需要在循环内部执行Math函数。

for(var i = 0; i < 6; i++) {
    document.write(Math.floor(Math.random()*41) + "<br>");
}

You don't need to increment your counter twice. 您无需两次增加计数器。 Also, the random() needs to be inside your loop. 另外,random()必须位于循环内。

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

for(var i=0; i<6; i++){
    document.write(x + "</br>");
    x = Math.floor(Math.random()*41);
}

you are assigning the var x with a random number before starting the loop, it remains same throughout the execution 您在开始循环之前为var x分配了一个随机数,它在整个执行过程中保持不变

try placing it inside the loop,also about incrementing the i, you are doing it in the for loop already so you do not need to do it inside the loop 尝试将其放置在循环中,也要增加i,您已经在for循环中进行了操作,因此您无需在循环内进行操作

var x = Math.floor(Math.random()*41);//place it inside the loop

for(var i=0; i<7; i++){
    document.write(x + "</br>");
    i++;//remove this
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM