2016-09-18 78 views
1
animations = ['fadeIn','fadeInDown','slideInUp','flipInY','bounceInLeft']; 

想象我产生每当用户点击的东西,所以要达到最佳体验,我希望用户拥有相同的效果随机效应。但与避免相同的值使用的Math.random再次出现()

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

会发生。

如何避免同一个值再次出现?

+0

你有5种效果。显示相同的价值是很自然的。你可以提供更多关于'如何避免同一个值再次出现的细节' –

+0

你可以为效果索引设置一个变量i,然后为动画设置动画(或其副本)到动画.splice(i,1)。如果数组变空,则需要重新开始所有动画。 –

+1

你也确定你想要-1吗? –

回答

3

两种方式,我可以建议。

  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

0

正在关注@Redu和我的评论,请在使用它之后拿出来,但是在副本上工作。

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 
 
    } 
 
}

+0

'remove'做什么? –

+0

和animations.slice()返回与动画相同的值。那么slice()是什么? –

+0

删除了从tmp中删除了多少项目。当所有的动画都被删除后,我们需要重置tmp来做所有的动画并重新开始。 animations.slice不会返回与动画相同的值,但它是一个副本,不会与原始数组混淆,如果您想在其他地方使用它,并且希望重置tmp并且不想拥有这两个副本失去了重置它的内容。 –

0

我建议使用不同的方法,通过存储最后两个选定的元素并选择与最后选择的项目不同的一个。

这可以防止原始数组的切片和操作。

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; }

+0

这是更清洁。但'〜'做什么? –

+0

我没有得到这一行以及'last.length === 2 && last.shift();' –

+1

'〜'是一个按位不是运算符,它是检查'!== -1 '。更多[这里](http://stackoverflow.com/a/36156654/1447675)。第二种是简短形式的'if(last.length === 2){last.shift(); }'。 –

相关问题