I have an 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) {
  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);

Some more info about the algorithm used.

Javascript相关问答推荐

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

在页面上滚动 timeshift 动垂直滚动条

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

Chrome是否忽略WebAuthentication userVerification设置?""

如何使用JavaScript将文本插入空div

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

函数返回与输入对象具有相同键的对象

未捕获错误:[]:getActivePinia()被调用,但没有活动Pinia.🍍""在调用app.use(pinia)之前,您是否try 使用store ?""

如何避免页面第一次加载时由于CSS样式通过JavaScript更改而出现闪烁

使用原型判断对象是否为类的实例

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

如何在Svelte中从一个codec函数中调用error()?

无法检索与Puppeteer的蒸汽游戏的Bundle 包价格

如何修复错误&语法错误:不能在纯react 项目中JEST引发的模块&之外使用导入语句?

Angel Auth Guard-用户只有在未登录时才能访问登录页面,只有在登录时才能访问其他页面

为什么我的SoupRequest";被重置为初始值,以及如何修复它?

我如何才能获得价值观察家&对象&S的价值?

如何向内部有文本输入字段的HTML表添加行?

当达到高度限制时,如何裁剪图像?使用html和css

不允许在对象文本中注释掉的属性