-2 javascript random loops function
当我尝试循环某些函数时,它会卡在 randomvariable() 上,随机数如何在循环中工作而无需每次都刷新页面
function randomvariable() {
randomvariable = Math.floor(Math.random() * 21);
document.getElementById("demo").innerHTML = randomvariable;
}
function launchfunctions() {
var count = 0;
while (count < 10) {
randomvariable();
count++;
}
}
launchfunctions();Run Code Online (Sandbox Code Playgroud)
<div id="demo" ></div>Run Code Online (Sandbox Code Playgroud)
您正在重新定义randomvariable、使用var或调用其他变量。
function randomvariable() {
var randomvariable = Math.floor(Math.random() * 21);
document.getElementById("demo").innerHTML = randomvariable;
}
Run Code Online (Sandbox Code Playgroud)
或者
function randomvariable() {
mynum = Math.floor(Math.random() * 21);
document.getElementById("demo").innerHTML = mynum;
}
Run Code Online (Sandbox Code Playgroud)
尽管请注意var在定义变量时应始终使用关键字,但在第二个示例中已省略它以显示仅调整变量名称如何解决问题。
笔记:
var在非严格模式下声明一个变量将使其成为全局变量。这就是在var函数内部使用会起作用的原因。| 归档时间: |
|
| 查看次数: |
4862 次 |
| 最近记录: |