[英]Javascript shuffle function returns same value in for loop
為什么在for循環中使用shuffle函數對三個數組進行排序時,為什么我得到的順序相同?
var items = ['x', 'y', 'z', 'a', 'b'];
var createSlots = function(slots)
{
slots = slots || 3;
var slotRack = [];
for (var i = 0; i < slots; i++ )
{
slotRack.push(shuffle(items));
}
return slotRack;
}
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var slotmachine = createSlots();
// returns three arrays with values in the same order... do not want that... :(
console.log(slotmachine);
squint
在上面的評論中指出了您的問題。
無論如何,這是一個更酷的隨機播放方法,它總是會讓您擺脫麻煩:
function shuffle(arr) {
return arr.sort(function () {
return Math.random() - Math.random()
});
};
編輯 (感Mr. Llama
):
改用Fisher-Yates改編 (感謝Christoph
的實現):
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
您在循環的每次迭代中都推送對同一數組的引用,請嘗試以下操作:
slotRack.push(shuffle(items.slice()));
在這里查看: JSFiddle
編輯:也許最好在函數中執行slice()
,所以返回o.slice()
,使用函數時不必擔心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.