2014-12-15 2 views
0

아래의 셔플 기능이 올바르게 작동하지 않습니다. 난 100 + 페이지의 배열을 가지고 셔플하고 다음 특정 시간 동안 iframe에 표시해야합니다. 어떻게 든 그것은 100+ 페이지의 전체 배열을 보여주지는 못하지만 약 25 페이지가 지나면 다시 시작하는 것처럼 보입니다. 누구든지 도와 줄 수 있습니까? 전체 배열이 항상 항상 새로운 무작위 순서로 재생되는지 확인해야합니다 (페이지가 방문 될 때마다 임의 순서로 이동하고 전체 배열을 재생 한 후 임의 재생).Javascript - 셔플 배열이 올바르게 작동하지 않습니다. 도움이 필요합니다

다음은 코드입니다. 잘못 가고 어디에 사람이 볼 수

<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 /> 
+0

셔플이 방법을 사용하여 http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript. – Deshan

+0

내 코드에서 어떻게 구현합니까? 셔플과 pageChange 함수를 결합하는 법을 모르겠습니다. – TVB

답변

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/

+0

감사합니다. 내 셔플 섹션을 코드로 대체하지만 iframe에서는 아무 일도 일어나지 않습니다. – TVB

+0

다음을 시도해보십시오. http://jsfiddle.net/u9y4pxwz/ – nobe4

+0

예! 바이올린에서는 훌륭하게 작동하지만 내 자신의 코드에서'pageChange();'를'onload = pageChange; '로 변경해야합니다. 시작하기도하고 첫 페이지가 항상 오류/비 존재 함 페이지. 그것의 두 번째 페이지에서 셔플을 연주하는 것 같다 ... – TVB