Javascript shuffle函数在for循环中返回相同的值

时间:2014-10-28 14:59:56

标签: javascript

为什么我在同一个顺序中获得三个数组,而我在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);

2 个答案:

答案 0 :(得分:2)

squint在上面的评论中陈述了您的问题。

无论如何,这是一个更酷的洗牌方法,总能让你摆脱困境:

function shuffle(arr) {
    return arr.sort(function () {
        return Math.random() - Math.random()
    });
};

编辑(感谢&#39; s Mr. Llama):

使用Fisher-Yates shuffle(感谢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;
}

答案 1 :(得分:1)

您正在循环的每次迭代中推送对同一数组的引用,请尝试以下方法:

 slotRack.push(shuffle(items.slice()));

请在此处查看:JSFiddle

编辑:也许最好在你的函数中执行slice(),所以返回o.slice()并且在使用该函数时你不必担心它。

相关问题