事实生成器(非随机)

时间:2018-02-22 17:07:22

标签: javascript function random

我正在为我公司的页面添加一个随机事实生成器。它目前看起来像这样:

var targetemployee = document.getElementById('targetemployee');
    var factsemployee = [

      'Fact1',
      'Fact2',
      'Fact3',
      'Fact4',
      'Fact5',
    ];
    function newEmployeeFact () {
      var i = Math.floor(Math.random() * factsemployee.length) | 0;
      targetemployee.innerText = factsemployee[i]

    }
    
    newEmployeeFact();
    <div style="text-align: center;">

    <p class="funfact" id="targetemployee"></p><button type="button" class="hover-shadow" style="text-align: middle; font-size: 0.8em; bottom: 0px" onclick="newEmployeeFact()"> NEW FACT </button>

    </div>

我的问题是,点击几次后,它有时会显示相同的事实,而不是一个新事实,所以我只想改变它是顺序的。有小费吗?我是一名JS初学者,所以我很感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

var targetemployee = document.getElementById('targetemployee');

var factsOrig = [
    'Fact1',
    'Fact2',
    'Fact3',
    'Fact4',
    'Fact5',
  ];

var factsemployee = factsOrig.slice(0);

function newEmployeeFact () {
    if (!factsemployee.length) {
        factsemployee = factsOrig.slice(0); // Refill array
    }
    var i = Math.floor(Math.random() * factsemployee.length) | 0;
    targetemployee.innerText = factsemployee[i]
    factsemployee.splice(i, 1); // Remove from active array
}

newEmployeeFact();
<div style="text-align: center;">

<p class="funfact" id="targetemployee"></p><button type="button" class="hover-shadow" style="text-align: middle; font-size: 0.8em; bottom: 0px" onclick="newEmployeeFact()"> NEW FACT </button>

</div>