Mar*_*arf 2 javascript arrays random shuffle angular
我试图在我的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>
Run Code Online (Sandbox Code Playgroud)
打字稿
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道是否有一个简单的解决方案,但我真的希望有人能够帮助我...
谢谢
Sha*_*sai 10
我认为问题是你需要做一些事情:
this.cards.sort((a,b) => 0.5 - Math.random());
Run Code Online (Sandbox Code Playgroud)
或者做这样的事情:
this.cards.sort(() => Math.random() - 0.5);
Run Code Online (Sandbox Code Playgroud)
基于此SE查询
| 归档时间: |
|
| 查看次数: |
4687 次 |
| 最近记录: |