溫馨提示×

能否用js隨機數實現隨機排序

js
小樊
94
2024-10-09 21:45:20
欄目: 編程語言

當然可以。您可以使用Fisher-Yates洗牌算法來實現隨機排序。以下是使用JavaScript實現的示例:

function shuffleArray(array) {
  let currentIndex = array.length, temporaryValue, randomIndex;

  // 當還剩元素待處理時
  while (0 !== currentIndex) {
    // 選取一個剩余元素
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // 交換當前元素與選取的元素
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// 使用示例
const myArray = [1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(myArray);
console.log(shuffledArray);

這個函數接受一個數組作為參數,然后使用Fisher-Yates算法對其進行隨機排序。您可以用這個函數來隨機排序任何數組。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女