[英]How can I shuffle a JavaScript array?
我試圖在我的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>
打字稿
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);
}
}
我不知道是否有一個簡單的解決方案,但我真的希望有人能夠幫助我...
謝謝
我認為問題是你需要做一些事情:
this.cards.sort((a,b) => 0.5 - Math.random());
或者做這樣的事情:
this.cards.sort(() => Math.random() - 0.5);
基於此SE查詢
試試這個隨機播放功能。
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;
}
它是一個純函數,可以在任何數組上使用。 它將創建一個新的混洗數組,保留原始數組。
如果你要讓它在你的模板工作,所以它按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)Shuffle”。 我必須使用Fisher-Yates shuffling算法作為參考。
您可以采用的一個可能的解決方案是創建一個函數來生成隨機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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.