網站搜尋

javascript - 我如何打亂一個陣列?


我想在 JavaScript 中像這樣隨機排列一個元素陣列:

[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]

答案#1

使用費雪-耶茨洗牌演算法的現代版本:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) 版本

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

然而,請注意,從2017年10月起,使用解構賦值交換變數會導致顯著的性能損失。

使用

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

實作原型

使用 Object.defineProperty(方法取自這個 SO 回答),我們也可以將這個函數實作為陣列的原型方法,而不會讓它出現在像 for (i in arr) 這樣的迴圈中。以下將允許你呼叫 arr.shuffle() 以打亂陣列 arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

答案#2

您可以使用費雪-耶茨洗牌演算法(代碼改編自此網站):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}