javascript - 运行循环显示结果
问题描述
如何使用循环将硬币翻转 20 次,每次将翻转结果显示为页面上的字符串?循环完成后,我想用每次翻转的结果返回数组。
到目前为止我所拥有的:
function display20Flips() {
const results = [];
var i;
var results = '';
for (i = 0; i < 20; i++) {
}
const coin = {
state: 0,
flip: function() {
this.state = Math.floor(Math.random() * 2);
},
toString: function() {
if (this.state === 0) {
return Heads;
} else {
return Tails
}
},
toHTML: function() {
const image = document.createElement('img');
image.src = `$this.toString()}.png`
image.alt = this.toString()
return image;
}
};
function display20Flips() {
const results = [];
// 4. One point: Use a loop to flip the coin 20 times, each time displaying the result of the flip as a string on the page. After your loop completes, return an array with the result of each flip.
for (let i = 0; i < 20; i++) {
if(i%2){
results[i] = 'heads';
} else{
results[i] = 'tails';
}
console.log(results[i])
}
}
display20Flips();
function display20Images() {
const results = [];
// 5. One point: Use a loop to flip the coin 20 times, and display the results of each flip as an image on the page. After your loop completes, return an array with result of each flip.
}
解决方案
您可能想要创建一个确定值的 FlipCoin 函数,在循环中调用此函数,将函数结果值存储在一个变量中,您可以将其打印到屏幕上并添加到结果数组中。
像这样的东西
// Returns 1 or 0, i.e. 1 = Head, 0 = Tail
function flipCoin() {
var flipValue = Math.floor(Math.random() * 100);
return flipValue % 2;
}
function main() {
let results = [];
for (cnt = 0; cnt < 20; cnt++) {
let result = flipCoin();
results.push(result);
console.log(result == 0 ? "Tail" : "Head");
}
console.dir(results);
}
main();
推荐阅读
- r - 使用条件文件路径编写 .xlsx 文件
- android - 检测手机的方向
- python-3.x - Selenium Python 浏览上下文已被丢弃。使用 Firefox 和 GeckoDriver
- ios - CNContactViewController 取消按钮在 iOS 13 中不起作用
- jquery - 如何使用 Jquery 中的类获取和放置这些特定字段的值
- regex - 用于提取特定接口的正则表达式
- azure - 如何一次性获取与 azure logic app 运行或执行相关的所有操作结果?
- python - django 通过 LDAP 进行用户身份验证
- c++ - 我想仅使用递归将字符“a”替换为字符“z”
- sql - Oracle SQL:是否可以使用 SUBSTR 和 INSTR 返回给定文本字段中的所有字符串?