本文介绍了如何随机(随机播放)JavaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组是这样的:

I have one array like this:

var arr1 = ["a", "b", "c", "d"];

如何可以随机播放/随机播放了吗?

How can I randomize / shuffle it?

推荐答案

事实上的公正洗牌算法是费雪耶茨(又名高德纳)洗牌。

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

请参阅

您可以看到一个(和原来的职位的)

You can see a great visualization here (and the original post linked to this)

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

用于像这样

var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

一些更多的信息所使用的算法。

这篇关于如何随机(随机播放)JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 17:36
查看更多