首頁  >  問答  >  主體

如何隨機化數組的順序?

我想在 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]


#
P粉512526720P粉512526720373 天前533

全部回覆(2)我來回復

  • P粉590428357

    P粉5904283572023-10-12 16:14:29

    您可以使用Fisher-Yates Shuffle(程式碼改編自此網站):

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

    回覆
    0
  • P粉316110779

    P粉3161107792023-10-12 10:21:15

    使用現代版本的 Fisher–Yates 洗牌演算法

    /**
     * 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;
        }
    });

    回覆
    0
  • 取消回覆