简体   繁体   English

随机数组重复索引项

[英]Random Array Repeats Index Items

This code works fine in their example but repeats some of my index items when I try and use it. 这段代码在他们的示例中运行良好,但是当我尝试使用它时会重复一些索引项。

var lastloaded = 0;
window.onload = loadPages;

    Array.prototype.knuthShuffle = function()
    {
        var i = this.length, j, temp;
        while ( --i )
        {
            j = Math.floor( Math.random() * (i - 1) );
            temp = this[i];
            this[i] = this[j];
            this[j] = temp;
        }
    };

var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];

function loadPages () {
     arr.knuthShuffle();
    var frame = document.getElementById("frameWrap");
    if (lastloaded+1>arr.length){
        lastloaded = window.location = "greatJob.html";
    }
    frame.src = arr[lastloaded];
    lastloaded++;
};
document.getElementById('tom').onclick = loadPages;

Can anyone tell me what I am missing from this code to keep it from repeating items in my array? 谁能告诉我这段代码中缺少的内容,以防止其在数组中重复出现?

I'm not sure I completely understand how your page works, but it seems like it is shuffling the array in order to figure out the next page to go to. 我不确定我是否完全了解您的页面的工作原理,但似乎是为了对下一页进行摸索,对数组进行了改组。 This means that it is newly shuffled with every page load, and you therefore have no guarantee as to the uniqueness of the pages - in fact, it would be extremely unlikely for you to get all the unique pages (1 in n!, to be precise) 这意味着每次加载页面时都会对其进行新的改组,因此您不能保证页面的唯一性-实际上,获得所有唯一页面(n中的1!)非常不可能。精确)

In order to ensure uniqueness, you MUST save the generated order, not just the index you were at. 为了确保唯一性,您必须保存生成的订单,而不仅仅是保存您所在的索引。

You have a problem with your declaration of j and temp which might add up on multiple shuffles and give you some strange behavior. 您对jtemp声明有问题,这可能会导致多次改组并给您带来一些奇怪的行为。

specifically this line: 特别是这一行:

 var i = this.length, j, temp; 

and these lines: 这些行:

 j = Math.floor( Math.random() * (i - 1) ); temp = this[i]; 

The problem here is that you didn't actually declare the j and temp variables, that's an invalid syntax. 这里的问题是您实际上没有声明jtemp变量,这是无效的语法。 Then when declaring them within your loop without the var keyword they are treated as global variables. 然后,在不使用var关键字的循环中声明它们时,它们将被视为全局变量。 Solvable by modifying the first line into: 通过将第一行修改为可解决:

 var j, temp; var i = this.length; 

Edit : Actually that isn't it, as already pointed out by t.niese every time you click tom you're re-shuffling. 编辑 :其实不是,正如t.niese每次点击tom所指出的那样,您正在重新洗牌。

What you want to do is shuffle once and use the newly shuffled array every time. 您想要做的是随机播放一次,然后每次都使用新随机播放的数组。 So decouple your shuffling from your page loading by taking arr.knuthShuffle(); 因此,通过使用arr.knuthShuffle();将混洗与页面加载arr.knuthShuffle(); out of the loadPages() function. loadPages()函数之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM