【发布时间】: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