首页 > 解决方案 > 运行循环显示结果

问题描述

如何使用循环将硬币翻转 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.
}

标签: javascript

解决方案


您可能想要创建一个确定值的 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();


推荐阅读