」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 我如何在JavaScript中有效地洗牌?

我如何在JavaScript中有效地洗牌?

發佈於2025-03-04
瀏覽:408

How Can I Efficiently Shuffle an Array in JavaScript?
與JavaScript

相反,Fisher-Yates Shuffle AlgorithM提供了一種有效的方法,用於在JavaScript中洗牌數組。通過隨機交換元素,它可以確保每個可能的訂購都有相等的發生機會。

; a [i] = a [j]; a [j] = x; } 返回a; } 此算法以相反的順序通過數組迭代,將每個元素與數組前面的隨機元素交換。 The resulting array is shuffled due to the random nature of the swaps.

Usage

The shuffle function can be used to shuffle an array using the following syntax:

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

es6版本

fisher-yates algorithm在es6:
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;
}
,this [j]] = [this [j],this [i]]; } 返回此; } });

此實現允許使用arr.shuffle()語法將數組改組。 [&& &&&&華

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3