避免使用math.random()再次出现相同的值

编程入门 行业动态 更新时间:2024-10-10 21:21:30
本文介绍了避免使用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?

推荐答案

我可以提出两种建议.

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

    本文发布于:2023-10-27 23:48:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1534883.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:math   random

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!