[英]How do I properly use a “for loop” to roll one die (or multiple) within a function of another die roll?
I'm a student and new to computer programing and had a quick question regarding a project I'm working on and how I am suppose to make it work. 我是一名学生,是计算机编程的新手,对我正在从事的项目以及如何使其正常运转有一个快速的问题。
This is what the requirement is: Instead of having two dice initially showing on the page, start with only one die image, and build the second image tag inside a for loop in your function. 这就是要求:不是在页面上最初显示两个骰子,而是从一个骰子图像开始,然后在函数的for循环内构建第二个图像标签。 Remove the first block of code (that rolls the first die) and instead put the code for the second die (the one that builds the img tag) into a "for" loop that runs twice.
删除第一个代码块(滚动第一个骰子),然后将第二个骰子的代码(构建img标签的代码)放入运行两次的“ for”循环中。
<script type="text/javascript">
//double dice script
function SelectImage2() {
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
document.getElementById('dieImg2').src = imgName2;
roll3 = Math.floor(Math.random() * 6) + 1;
imgName3 = '../images/die' + roll3 + '.gif';
document.getElementById('dieImg3').src = imgName3;
}
</script>
<div style="text-align:center">
<p>
<img id="dieImg2" alt="die image"
src="../images/die2.gif" >
<img id="dieImg3" alt="die image"
src="../images/die3.gif" >
</p>
<input type="button" value="Roll until doubles" onclick="SelectImage2();">
</div>
Basically, I guess I'm just looking for someone to maybe explain the for loop function and how I am suppose to call one roll within another roll? 基本上,我想我只是在找一个人来解释for循环功能,以及我应该如何在另一卷中调用一个卷? Any advice would be greatly appreciated!
任何建议将不胜感激! Thanks!
谢谢!
Use something like 使用类似
function SelectImage2() {
for (var i = 2; i <= 3; ++i) {
var roll = Math.floor(Math.random() * 6) + 1,
imgName = '../images/die' + roll + '.gif';
document.getElementById('dieImg' + i).src = imgName;
}
}
Or, if you want compact code, 或者,如果您需要紧凑的代码,
function SelectImage2() {
for (var i = 2; i <= 3; ++i) {
document.getElementById('dieImg' + i).src
= '../images/die' + ( 1 + Math.random() * 6 | 0 ) + '.gif';
}
}
Notes 笔记
var
! var
修饰变量! number|0
is a simple and fast way to round towards 0 number|0
是四舍五入的简单快速方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.