animations = ['fadeIn','fadeInDown','slideInUp','flipInY','bounceInLeft'];
Imaginez que je génère un effet aléatoire chaque fois que l’utilisateur clique sur quelque chose. Par conséquent, pour obtenir la meilleure expérience possible, j’aimerais que l’utilisateur ait le même effet. Mais avec
animations[ Math.floor(Math.random() * animations.length) -1];
cela arriverait.
Comment éviter que la même valeur réapparaisse?
Deux façons que je peux suggérer.
.slice()
) Array.prototype.shuffle = function(){ var a = this.slice(), // don't morph the original i = a.length, j; while (i > 1) { j = ~~(Math.random()*i--); a[i] = [a[j],a[j]=a[i]][0]; } return a; }; var album = ["photo1","photo2","photo3","photo4","photo5"]; photos = album.shuffle(); photos.forEach(p => console.log(p)); console.log("another way") // the splice way photos = album.slice(); while (photos.length) console.log(photos.splice(Math.floor(Math.random() * photos.length),1)[0]); !photos.length && (photos = album.slice()); // restore photos album and continue while (photos.length) console.log(photos.splice(Math.floor(Math.random() * photos.length),1)[0]); !photos.length && (photos = album.slice()); // restore photos album and continue
Après @Redu et mes commentaires, supprimez-le après l’avoir utilisé, mais travaillez sur une copie.
var animations = ['fadeIn', 'fadeInDown', 'slideInUp', 'flipInY', 'bounceInLeft']; var j; var tmp = animations.slice(); //copy var removed = 0; for (var i = 1; i < 20; i++) { j = Math.floor(Math.random() * tmp.length); console.log(tmp[j]); tmp.splice(j, 1); removed++; if (animations.length == removed) { tmp = animations.slice(); removed = 0 } }
Je suggère d’utiliser une méthode différente, en stockant les deux derniers éléments sélectionnés et en choisissant un élément différent des derniers éléments sélectionnés.
Cela empêche le découpage et la manipulation du tableau d’origine.
function Random(array) { var last = []; this.next = function () { var r; do { r = Math.floor(Math.random() * array.length); } while (~last.indexOf(r)) last.length === 2 && last.shift(); last.push(r); return array[r]; } } var animations = ['fadeIn', 'fadeInDown', 'slideInUp', 'flipInY', 'bounceInLeft'], random = new Random(animations), i; for (i = 0; i < 15; i++) { console.log(random.next()); }
.as-console-wrapper { max-height: 100% !important; top: 0; }