如何在Typescript中生成两个随机数并检查两者是否相同


import { Component, OnInit } from '@angular/core';
import { from } from 'rxjs';
@Component({
selector: 'app-play-match',
templateUrl: './play-match.component.html',
styleUrls: ['./play-match.component.css']
})
export class PlayMatchComponent implements OnInit {


public teams = [
"Annites Football Club","Devans Football CLub", "Marians Football Club",
"Loyolian Football Club","Avian Football Club"
];
public homeTeamSelect: number = Math.floor(Math.random() * this.teams.length);
public opponentTeamSelect:number = Math.floor(Math.random() * this.teams.length);

if (homeTeamSelect:number === opponentTeamSelect:number) {

}



constructor() { }
ngOnInit(): void {
this.loadScript('../assets/js/play.js')
}
public loadScript(url : string){
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}



}

如果区域抛出错误,则无法找到opponentTeamSelect。如何修复此错误?请帮帮我。我需要生成两个介于数组大小或数组长度之间的随机数,然后从这个数组中选择两个球杆并将其设置为变量。但在我的情况下,两个随机数不可能是相同的。所以有人能给我合适的解决方案吗?非常感谢。

添加一个while循环,重新计算,直到它们不同。

this.homeTeamSelect = Math.floor(Math.random() * this.teams.length);
this.opponentTeamSelect = Math.floor(Math.random() * this.teams.length);
while(this.homeTeamSelect === this.opponentTeamSelect) {
this.opponentTeamSelect = Math.floor(Math.random() * this.teams.length);
}

如果数组大小小于2,这将永远循环,所以你应该在中进行一些检查

最新更新