【问题标题】:How can I shuffle a JavaScript array?如何随机播放 JavaScript 数组?
【发布时间】:2026-02-02 17:35:02
【问题描述】:

我正在尝试在我的 Angular6 项目中随机化我的数组的顺序。我不知道该怎么做,最后尝试使用 Math.random() 函数对数组进行排序......(没用 XD)

这是我目前的代码:

HTML

    <div style="background: darkcyan; width: 600px; height: 600px; margin: auto">
  <table>
    <tr *ngFor="let card of cards">
      <div id="{{card.id}}" [ngStyle]="{'background-color': card.color}" style=" width: 100px; height: 125px; margin: 5px"></div>
    </tr>
  </table>
</div>
<button (click)="shuffle()">Shuffle Cards</button>

TypeScript

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-memory-game',
  templateUrl: './memory-game.component.html',
  styleUrls: ['./memory-game.component.css']
})
export class MemoryGameComponent implements OnInit {
  cards = [];
  constructor() { }

  ngOnInit() {
    this.cards = [
        {
          'id': 1,
          'color': 'red'
        },
        {
            'id': 2,
            'color': 'green'
        },
        {
            'id': 3,
            'color': 'blue'
        },
        {
            'id': 4,
            'color': 'yellow'
        }
    ];
      this.shuffle();
  }

  public shuffle() {
      this.cards.sort(Math.random);
  }
}

我不知道是否有一个简单的解决方案,但我真的希望有人能够帮助我..

谢谢

【问题讨论】:

  • Math.random 总是返回一个正数,所以结果不会是随机的。参考@Shan-Desai的回答来解决问题(从Math.random*.com/a/53066842/1423259减0.5

标签: javascript arrays angular random shuffle


【解决方案1】:

我认为问题在于您需要执行以下操作:

this.cards.sort((a,b) => 0.5 - Math.random());

based on some previous answers on SE

或者做这样的事情:

 this.cards.sort(() => Math.random() - 0.5);

基于此SE Query

【讨论】:

【解决方案2】:

您可以采取的一种可能的解决方案是创建一个函数来生成一个随机 int 并在您的 Array.prototype.sort 函数回调中使用它:

var cards = [{
    'id': 1,
    'color': 'red'
  },
  {
    'id': 2,
    'color': 'green'
  },
  {
    'id': 3,
    'color': 'blue'
  },
  {
    'id': 4,
    'color': 'yellow'
  }
];

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

cards.sort(function(a, b) {
  return getRandomInt(cards.length) - getRandomInt(cards.length);
});

console.log(cards);

【讨论】:

    【解决方案3】:

    试试这个随机播放功能。

    function shuffle(arrParam: any[]): any[]{
        let arr = arrParam.slice(),
            length = arr.length,
            temp,
            i;
    
        while(length){
            i = Math.floor(Math.random() * length--);
    
            temp = arr[length];
            arr[length] = arr[i];
            arr[i] = temp;
        }
    
        return arr;
    }
    

    它是一个纯函数,可以在任何数组上使用。 它将创建一个新的 shuffled 数组,保留原来的数组。

    如果你想让它在你的模板中工作以便它对this.cards进行排序,你可以使组件方法shuffle()改变this.cards

    public shuffle(): any[]{
        let arr = this.cards.slice(),
            length = arr.length,
            temp,
            i;
    
        while(length){
            i = Math.floor(Math.random() * length--);
    
            temp = arr[length];
            arr[length] = arr[i];
            arr[i] = temp;
        }
    
        this.cards = arr;
    }
    

    编辑:我检查了他在评论中提供的@wannadream 链接,看起来我上面的shuffle 函数是“事实上的无偏洗牌算法是Fisher-Yates(又名Knuth)洗牌”。我一定是使用 Fisher-Yates 洗牌算法作为参考编写的。

    【讨论】: