在 Safari 中,我认为 IE7 和 8 Math.random() 也不是随机的?

2024-02-22

http://koreanwordgame.com/ http://koreanwordgame.com/

此页面首先通过 Ajax 将 4 个单词加载到选项 DIV 中,然后使用以下函数随机化正确答案,传递包含要随机化的元素的 DIV 作为参数:

var random = function(r){
    r.children().sort(function(a,b){
      var temp = parseInt( Math.random()*10 );
      return( temp%2 );
    }).appendTo(r);            
};

random($("#option"));

<div id="option">   
<div class="option" id="option1" style="background-color: rgb(229, 232, 238); ">light</div>
<div class="option" id="option4" style="background-color: rgb(183, 190, 204); ">pot</div>
<div class="option" id="option2" style="background-color: rgb(183, 190, 204); ">garlic press</div>
<div class="option" id="option3" style="background-color: rgb(183, 190, 204); ">habitant</div>
</div>

问题是,在 Safari 中,正确答案总是位于顶部位置......

在 IE 7 和 8 中,它经常位于顶部位置。

我知道可以通过使用时间戳或其他东西来使函数“更加随机”,但我正在努力使其正常工作。


问题不是Math.random(). It's your“随机化”排序函数,只返回0 or 1, 永不-1。以下是如何在区间内正确生成随机 int[-1. 1], 基于MDC's getRandomInt功能 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random#Example:_Using_Math.random:

Math.floor(Math.random() * 3) - 1;

(简化自getRandomInt(-1, 1)).


也就是说,作为@32bitkid https://stackoverflow.com/users/373378/32bitkid评论说,right方法是使用 Fischer-Yates 洗牌 https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Safari 中,我认为 IE7 和 8 Math.random() 也不是随机的? 的相关文章

随机推荐