Rumah  >  Soal Jawab  >  teks badan

Bagaimana cara rawak susunan tatasusunan?

Saya mahu mengocok pelbagai elemen dalam JavaScript seperti ini:

[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 hari yang lalu530

membalas semua(2)saya akan balas

  • P粉590428357

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

    Anda boleh menggunakan Fisher-Yates Shuffle (kod disesuaikan daripada laman web ini):

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

    balas
    0
  • P粉316110779

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

    Menggunakan versi moden algoritma shuffling 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;
    }

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

    Tetapi ambil perhatian bahawa menggunakan memusnahkan pembolehubah swap setakat Oktober 2017, peruntukkan akan dikenakan penalti prestasi yang teruk.

    Gunakan

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

    Melaksanakan prototaip

    Menggunakan Object.defineProperty (Diambil daripada jawapan SO ini Object.defineProperty取自此SO答案的方法)我们还可以实现该函数作为数组的原型方法,而无需让它出现在诸如 for (i in arr) 之类的循环中。以下代码将允许您调用 arr.shuffle() 来随机排列数组 arr) kita juga boleh melaksanakan fungsi sebagai prototaip tatasusunan kaedah tanpa perlu ia muncul dalam gelung seperti for (i in arr). Kod berikut akan membolehkan anda mengocok tatasusunan arr dengan memanggil arr.shuffle():

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

    balas
    0
  • Batalbalas