2016-09-18 82 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(); }'。 –

相關問題