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 随机播放阵列内容的主要内容,如果未能解决你的问题,请参考以下文章

python 随机播放两个具有相同维度的阵列,以预先设置两个阵列之间的映射

c_cpp 384.随机播放阵列

php 随机播放阵列并吐出X号

在摇动时从我的阵列列表中播放随机歌曲时出现异常

javascript 随机阵列

如何创建随机数的多个阵列为JavaScript数据随机化?