Javascript - 随机数组无法正常工作。需要帮助

时间:2014-12-15 11:41:24

标签: javascript arrays iframe shuffle

我在下面的随机播放功能无法正常工作。我有一个100多个页面的数组需要被洗牌,然后在iframe中显示一段时间。不知何故,它并没有向我显示100多页的整个数组,但在大约25页之后它似乎重新开始。有人可以帮忙吗?我需要确保整个数组始终以完整的方式播放,并且始终以新的随机顺序播放(因此每次访问页面时都要进行随机播放,并在整个数组播放后进行随机播放。

以下是代码,任何人都可以看到它出错的地方吗?

<script type="text/javascript">
var pages=new Array();
pages[0]="01.html";
pages[1]="02.html";
pages[2]="03.html";
....etc
pages[100] ="100.html";

 var shuffle = function(){
         var shuffledPages = [];

         /*The first time rand is used, it will not allow you to pick the last value used last time.*/
         var rand = Math.floor((pages.length - 1) * Math.random());

         while(pages.length > 0){
             shuffledPages.push( pages.splice( rand, 1)[0] );  
             rand = Math.floor(pages.length * Math.random());
         }

         return shuffledPages;
 }




var time=33000; 
var currentIndex = 0; 

function pageChange() { 
    if(currentIndex == pages.length - 1){ 
        pages = shuffle(); 
        currentIndex = 0; 
    } 
    else{ 
        currentIndex++; 
    } 

    document.getElementById("frame").src=pages[currentIndex]; 
    setTimeout("pageChange()",time); 
}

onload=pages = shuffle();
onload=pageChange;

</script>

<iframe id="frame" src="" width="1555px" height="872px" hspace="0" vspace="0" frameborder="2" scrolling="no" ></iframe><br />

1 个答案:

答案 0 :(得分:0)

编辑:工作代码:

var pages=[];
pages[0]="http://example.com/";
pages[1]="http://www.iana.org/domains/reserved";
pages[2]="http://en.wikipedia.org/wiki/Main_Page";
pages[3]="http://en.wikipedia.org/wiki/Randomness";

 var shuffle = function(array){
     var shuffledPages = [];
     while(array.length){
         shuffledPages.push(array.splice(Math.floor(array.length*Math.random()),1));
     }
     return shuffledPages;
}


var time = 3300; 
var currentIndex = 0; 

function pageChange() { 
    if(currentIndex == 0){ 
        pages = shuffle(pages); 
        console.log(pages);
        currentIndex = pages.length; 
    }
    currentIndex--; 
    document.getElementById("frame").src=pages[currentIndex]; 
    console.log(currentIndex);
    setTimeout(function() { pageChange(); }, time);
};

pageChange();

小提琴:http://jsfiddle.net/xaa1qccm/

相关问题