如何在JavaScript中随机播放对象数组? [英] How to shuffle an array of objects in javascript?

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

问题描述

下面的代码适用于普通数组,但不适用于带有对象的数组吗?有人知道如何执行此操作吗?

The code below works for a normal array but not with an array with object does anybody knows how to do this?

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    let temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

const result = shuffle(array);

console.log(JSON.stringify(result));

推荐答案

尝试按以下代码段进行排序:

Try sorting like this snippet:

console.log( [
    { some: 1 },
    { some: 2 },
    { some: 3 },
    { some: 4 },
    { some: 5 },
    { some: 6 },
    { some: 7 },
  ]
  .sort( () => Math.random() - 0.5) );

回应Martin Omanders评论:这是根据 Fisher-耶茨算法

In reponse to Martin Omanders comment: here's a shuffle method according to the Fisher-Yates algorithm

for (let i=0; i<20; i+=1) {
  console.log(JSON.stringify(shuffleFisherYates([0,1,2,3,4,5,6,7,8,9])));
}

function shuffleFisherYates(array) {
  let i = array.length;
  while (i--) {
    const ri = Math.floor(Math.random() * (i + 1));
    [array[i], array[ri]] = [array[ri], array[i]];
  }
  return array;
}

可能会压缩到一个衬里(注释:该衬里不会在

Which may be condensed to a one liner (note: this one liner will not compile in the Google Closure Compiler with level advanced):

const shuffle = array => 
  [...Array(array.length)]
    .map((...args) => Math.floor(Math.random() * (args[1] + 1)))
    .reduce( (a, rv, i) => ([a[i], a[rv]] = [a[rv], a[i]]) && a, array);
    
for (let i=0; i<100; i+=1)
  console.log(JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])));

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆