javascript 随机播放阵列内容

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 随机播放阵列内容相关的知识,希望对你有一定的参考价值。

// Shuffle array contents in place using Fisher-Yates shuffle algorithm - Code from Stack Overflow answer
// @param {Array} arr - An array containing items to be shuffled

function shuffle(arr) {

  // counter == number of elements in arr
  let counter = arr.length;
  
  // while elements in arr remain unswapped
  while (counter > 0) {
    
    // get random idx value to pick element from arr
    let idx = Math.floor(Math.random() * counter);
    
    // Decrease counter
    counter--;
    
    // swap last element in array with randomly selected idx element
    let temp = arr[counter];
    arr[counter] = arr[idx];
    arr[idx] = temp;
    // console.log(`Loop: ${counter}, Index: ${idx}, Counter Element: ${arr[counter]}, Swap Index: ${arr[idx]}`);
    
  } 
 
  return arr;
}

shuffle([1, 5, 6, 8, 2, 3, 5]);
// >>> [5, 8, 3, 2, 6, 1, 5]
// as always, this can be assigned to a variable i.e. let shuffledArray = shuffle([1, 2, 3, 4, 5, 6]);

以上是关于javascript 随机播放阵列内容的主要内容,如果未能解决你的问题,请参考以下文章