首页 > 解决方案 > 无法在数组中获取随机项(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];
    }
}

标签: angulartypescriptionic-framework

解决方案


只是为了发布一个完整的解决方案:如评论中所述,您可以简单地使用现有的 shuffle 函数并在构造函数或 ngOnInit 函数中访问它(Angular 的方式)。我把你的抽认卡放在一个新的并在洗牌后var设置它(稍后在你的 html 中使用)。这将确保数组在显示之前是随机播放的:this.flashCardsthis.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]都不是正确的方法。

祝你好运!


推荐阅读