JavaScript >> Javascript 文檔 >  >> Tags >> DOM

如何在 JavaScript 中隨機化/打亂數組 [示例]

本文將向您展示幾種在 JavaScript 中隨機化/打亂數組的簡單和復雜方法。

隨機化數組的快速而骯髒的方法

如果你不太關心所涉及的概率,這段代碼是一種快速隨機化數組內容的方法:

// Function to return a shuffled copy of a given array
function shuffle(array) {
    var shuffled = [...array]; // Make a copy of the array to be shuffled so that the original is not altered by the sort() function below
    shuffled.sort(() => Math.random() - 0.5); // Sort the array using the sort() method with random input from Math.random()
    return shuffled; // Return the shuffled copy of the array
}

它是這樣使用的:

var fruitArray = ['peach', 'apple', 'banana', 'pear']; // Create an array of fruit
shuffledFruit = shuffle(fruitArray); // Shuffle it and assign the returned value to a new variable
console.log(shuffledFruit); // Will print the shuffled copy of the array

然而,這種方法並不是真正的 隨機 - 這是 sort() 中的一個弱點 在 JavaScript 中實現的方法。 Math.random() 功能也不是完全 隨機的。

但是,這種方法足夠好 對於您不太關心效率或隨機性的基本場景,例如隨機化班級學生的座位順序或遊戲中玩家的顏色。另一方面,如果您正在編寫彩票程序或在其他一些概率和公平性很重要的場景中工作,您將需要使用不同的方法。

JavaScript 中的現代 Fisher-Yates Shuffle(正確方法)

Fisher-Yates 是一種隨機化/改組 的項目序列的方法 真正隨機。這是最好的方法,但它需要一些額外的編碼,因為 JavaScript 沒有內置實現。

至於為什麼 更好嗎?我建議查看 Wikipedia 文章以獲得正確的解釋。但是,我會堅持代碼:

// Function to return a shuffled copy of a given array (Fisher-Yates)
function shuffle(array) {
    var shuffled = [...array]; // Make a copy of the array to be shuffled so the original is not altered
    for (var i = shuffled.length - 1; i > 0; i--) { // Loop through each index (position) in the array
        var j = Math.floor(Math.random() * (i + 1)); // Pick an index randomly from the array
        var temp = shuffled[i]; // Store the value at the current index
        shuffled[i] = shuffled[j]; // Replace the value at the current position with the one at the randomly picked index
        shuffled[j] = temp; // Replace the value at the randomly picked index with the one which was at the current index (swapping them!)
    }
    return shuffled; // Return the shuffled array
}

使用方式與上例相同:

var fruitArray = ['peach', 'apple', 'banana', 'pear']; // Create an array of fruit
shuffledFruit = shuffle(fruitArray); // Shuffle it and assign the returned value to a new variable
console.log(shuffledFruit); // Will print the shuffled copy of the array


下一篇
No
Tutorial JavaScript 教程
  1. Wonder Wanderer 2 的開發日誌:第 11 天 #LOWREZJAM 😁

  2. 2021 年 Particles.js 還好嗎?

  3. 為您的 SaaS 初創公司選擇合適的技術堆棧

  4. 如何在 Github Actions 上設置 Cypress

  5. Minisauras:一個用於縮小 CSS 和 JS 文件的 Github 操作

  6. Angular 中的常見塊

  7. 是否可以從 ExtendScript 外部執行 JSX 腳本?

  1. 使用 Jest 在 React 中測試組件:基礎

  2. Advent.js🎅🏼| #25:最後一場比賽,明年見

  3. 2019 年 4 大 JavaScript 主要發展趨勢

  4. LIVE SHOW - Angular 中的漸進式 Web 應用程序#PWA

  5. 控制台日誌(9007199254740992 + 1);對結果感到驚訝?

  6. JSX 簡介 |第 2 天

  7. 使用 React 顯示 MapBox 地圖。 🗺️

  1. 為樂趣和利潤而進行的 Dom 遍歷

  2. 離子反應 - 第一眼

  3. Selenium C# 教程:處理警報窗口

  4. 樣式化組件 React Js