2014-05-18 4 views
1

내가 어떤 배열을 가지고 있고, 내 모든 배열이 하나 개의 큰 배열로 연결될 수 싶어하지만 셔플 (as explained here)CONCAT의 배수

를 사용하여 randomise 할 그들을 통과 자바 스크립트에서 하나 개의 큰 임의 배열에 배열을 단행 배열을 하나씩

는 지금은 눈치도이 :

var proxies = [ 
     {stim: A}, 
     {stim: B}, 
     {stim: C}, 
     {stim: D}] 
var a = shuffle(proxies); var b = shuffle(proxies); var c = shuffle(proxies); 
var x = a.concat(b, c) 

도 그 :

var x = shuffle(proxies).concat(shuffle(proxies), shuffle(proxies)) 

내 초기 프록시 배열의 세 가지 다른 단행 순서로 구성되어 더 큰 배열을 생산 않습니다.

콘솔에 로그인하면 두 옵션 모두 항상 셔플 주문이 세 번 반복됩니다. 한 번만 섞어서 그 순서대로 남아있는 것처럼 보입니다.

해결 방법에 대한 아이디어?

답변

1

질문에 언급 한 게시물의 기능을 사용하려면 약간 수정해야합니다. 코드는

<script type="text/javascript"> 
    function shuffle(array) { 
     var newarr=[] 
     var currentIndex = array.length, 
     temporaryValue, 
     randomIndex; 
     while (0 !== currentIndex) { 
     randomIndex = Math.floor(Math.random() * currentIndex); 
     currentIndex -= 1; 
     temporaryValue = array[currentIndex]; 
     array[currentIndex] = array[randomIndex]; 
     newarr[currentIndex] = array[randomIndex] 
     array[randomIndex] = temporaryValue; 

     } 

     return newarr; 
    } 

    var proxies = [{stim:'a'},{stim: 'b'},{stim: 'c'},{stim: 'd'}] 
    var a=shuffle(proxies); 
    var b=shuffle(proxies); 
    var c=shuffle(proxies); 
    var x=a.concat(b, c) 
    console.log(x) 
</script> 
입니다.
0

마치 shuffle() 함수가 지정된 배열에서 작동하고 새 배열을 생성하지 않는 것처럼 보입니다. 첫 번째 예에서 a, b 및 c는 모두 동일한 배열과 같습니다.

고유 한 3 개의 셔플을 만들고 싶다면 셔플 링 및 연결하기 전에 어레이를 복제/복사해야합니다. 많은 옵션이 있습니다. 예 : How do you clone an Array of Objects in Javascript?