【发布时间】:2020-08-31 05:20:06
【问题描述】:
我正在尝试从 flashCards 数组中随机化项目(包含英文单词的卡片),以便在用户重新加载页面时每张卡片都可以随机出现。我使用过 Math.floor(Math.random()) 函数,但它不起作用。如何从一组卡片中随机获取卡片?
home.page.html:
<ion-content padding>
<app-flash-card *ngFor="let card of flashCards" [ngClass]="randomize()">
<div class="flash-card-front">{{card.front}}</div>
<div class="flash-card-back">{{card.back}}</div>
</app-flash-card>
</ion-content>
home.page.ts:
export class HomePage {
flashCards: any;
constructor(public navCtrl: NavController) {
this.flashCards = [
{back: 'accreditation', front: 'offizielle Zustimmung'},
{back: 'AIDA', front: 'Attention, Interest, Desire, Action (Aufmerksamkeit, Interresse, Wunsch, Handlung)-> Modell zur Werbewirkung'},
{back: 'airtime', front: 'Sendezeit'},
{back: 'ambient noise', front: 'Umgebungsgeräusch'},
{back: 'ambitious', front: 'ehrgeizig,strebsam'}
];
};
randomize(){
var cards=this.flashCards[Math.floor(Math.random()*this.flashCards.length)];
return this.flashCards[cards];
}
}
【问题讨论】:
-
你想在打印它们的内容之前随机化数组吗?
-
是的,我想随机化数组
-
你可能对 this 感兴趣,在构造函数或 OnInit 上随机化数组。
-
您也错误地使用了指令 ngClass,它们是用于类的,请阅读它们here
-
shuffle(flashCards) { var currentIndex = this.flashCards.length,temporaryValue,randomIndex; // 虽然还有剩余的元素要洗牌... while (0 !== currentIndex) { // 选择一个剩余的元素... randomIndex = Math.floor(Math.random() * currentIndex);当前索引-= 1; // 并将其与当前元素交换。临时值=闪存卡[当前索引];闪存卡[当前索引] = 闪存卡[随机索引];闪存卡[随机索引] = 临时值; } 控制台.log(闪存卡);归还抽认卡; }
标签: angular typescript ionic-framework