1

レストランのランダムジェネレーターを作成しています。データベース内の場所を取得する PHP リクエストがあり、それらを json 配列に変換します。

次に、レストランを.sliceでランダムに表示して、今持っていた場所を削除するjquery関数があります。

$(document).ready(function() {

 // The "restos" var equals to my full json            
 var restos = <? echo $restos; ?>;

 function getRandomResto(){

        var randomKey = Math.floor(Math.random()*restos.length);
        var resto = restos[randomKey];
        restos.splice(randomKey, 1);

        var title = resto.title;

       //Add content
       $('#place').html('<h2>' + title + '</h2>');

    }
)};

これはショートバージョンです。

私がやりたいことは、配列が空になったら、再読み込みしてレストランのランダム表示を再開することです。

json var を再度呼び出そうとしましたが、関数内で restos.length が 0 に等しいが、それは良い解決策ではないようです...

どんな助けでも本当に感謝します!

4

1 に答える 1

0

次のように、毎回 resto を複製する必要があります。

 var restos = <? echo $restos; ?>;
 var currentRestos = restos.slice(0); // this clones an array

 function getRandomResto(){

       if (currentRestos.length == 0) {
         currentRestos = restos.slice(0);
       }

        var randomKey = Math.floor(Math.random()*currentRestos.length);
        var resto = currentRestos[randomKey];
        currentRestos.splice(randomKey, 1);

        var title = resto.title;

       //Add content
       $('#place').html('<h2>' + title + '</h2>');

    }
)};
于 2013-11-02T19:22:32.753 に答える