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

问题描述

我有一个这样的数组:

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

我怎样才能随机化/洗牌它?

How can I randomize / shuffle it?

推荐答案

事实上的无偏洗牌算法是 Fisher-Yates(又名 Knuth)洗牌.

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

参见 https://github.com/coolaj86/knuth-shuffle

您可以在这里看到很棒的可视化(以及原始帖子 链接到此)

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

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

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

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

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

  return array;
}

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

关于所用算法的更多信息.

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

05-28 17:35