【问题标题】:Javascript - Shuffle array not working correctly. Help neededJavascript - Shuffle 数组无法正常工作。需要帮助
【发布时间】:2014-12-15 11:41:23
【问题描述】:

我在下面的随机播放功能无法正常工作。我有一个包含 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 />

【问题讨论】:

标签: javascript arrays iframe shuffle


【解决方案1】:

编辑:工作代码:

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/

【讨论】:

  • 谢谢。我用你的代码替换了我的 shuffle 部分,但现在 iframe 中没有任何反应。
  • 是的!在小提琴中效果很好,但是在我自己的代码中,我需要将pageChange(); 更改为onload=pageChange; 才能启动,当它启动时,第一页始终是错误/不存在的页面。从第二页开始,它似乎在随机播放……
  • 我在小提琴中看到它在每个数组中也捕获了一个 404。
  • 我清楚地看到“错误 404 我们真的很抱歉,但没有这样的页面。”在第一个页面加载和每次下一次随机播放时。我认为数学在数组之外创建了一个值(零减一 -> 引用页面 [-1],它不存在。它只是在你身边以随机循环播放 4 页吗?
  • 现在呢? jsfiddle.net/xaa1qccm 我发现第一个值总是 4 作为数组长度,所以这个版本应该可以工作。
猜你喜欢
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 2011-11-23
相关资源
最近更新 更多