避免使用math.random()再次出现相同的值 [英] avoid same value to appear again using math.random()

查看:440
本文介绍了避免使用math.random()再次出现相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

animations = ['fadeIn','fadeInDown','slideInUp','flipInY','bounceInLeft'];

想象一下,每当用户单击某个内容时,我都会产生随机效果,因此,为了获得最佳体验,我希望用户也具有相同的效果.但是使用

Imagine I generate random effect whenever user click something, so to achieve best experience, I would want the user to have same effect. But with

animations[ Math.floor(Math.random() * animations.length) -1];

那会发生的.

如何避免相同的值再次出现?

How to avoid same value to appear again?

推荐答案

我可以提出两种建议.

  1. 首先对数组进行随机排序,然后从索引0到5逐一遍历,然后根据需要进行多次循环.
  2. 选择一个随机元素并将其切成薄片,直到阵列为空,然后从备份中刷新阵列. (请注意,不要使用参考进行备份,否则备份阵列会随着拼接而被删除.因此请使用.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

这篇关于避免使用math.random()再次出现相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆