angular - 无法在数组中获取随机项(Angular 10)
问题描述
我正在尝试从 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>
主页.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];
}
}
解决方案
只是为了发布一个完整的解决方案:如评论中所述,您可以简单地使用现有的 shuffle 函数并在构造函数或 ngOnInit 函数中访问它(Angular 的方式)。我把你的抽认卡放在一个新的并在洗牌后var
设置它(稍后在你的 html 中使用)。这将确保数组在显示之前是随机播放的:this.flashCards
this.flashCards
import { OnInit } from '@angular/core';
export class HomePage implements OnInit {
flashCards: any;
constructor(public navCtrl: NavController) { }
ngOnInit(): void {
var 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'}
];
this.flashCards = this.shuffle(flashCards)
}
shuffle (array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
}
此外,删除你的[ngClass]
,然后这样写:
<ion-content padding>
<app-flash-card *ngFor="let card of flashCards">
<div class="flash-card-front">{{card.front}}</div>
<div class="flash-card-back">{{card.back}}</div>
</app-flash-card>
</ion-content>
改组已完成,ngOnInit
无论如何[ngClass]
都不是正确的方法。
祝你好运!
推荐阅读
- ansible - Ansible 变量未在不匹配的条件下更新
- python - 使用命令“pip3 install --upgrade pip”进行 pip 升级后出错
- spring - p:calendar 组件没有提交选中的值,抛出 throws NullPointerException
- android - 两个日期之间的差异无法正常工作?
- javascript - 如何使用 javascript 删除特定的 div
- entity - hits@k 是如何计算的,在知识库中的链接预测上下文中意味着什么
- python - Jupyter Notebook:如何在函数外使用 ipython 小部件变量
- c# - 为匿名类上课的快速方法
- python - 如何使用 argparse 模块?
- reactjs - 使用 React/Redux 每分钟发出一个请求