Tips for creating two random numbers on Typescript and verifying if they match

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);

  }
  

 
  

}

I encountered an issue where the code cannot find the opponentTeamSelect variable in the if area. How do I resolve this error? Please provide me with guidance. I am attempting to generate two random numbers within the range of the team array length and assign two clubs from the array to variables. However, I require the two random numbers to be distinct. Can someone offer a correct solution for this scenario? Thank you.

Answer №1

Create a while loop that continues to recalculate until two different values are achieved.

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);
}

If the array size is less than 2, the loop will continue indefinitely, so make sure to include some checks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Can we access global variables directly in an Angular 2 HTML template?

After setting the app.settings as shown below public static get DateFormat(): string { return 'MM/DD/YYYY';} I need to utilize it in one of my HTML templates for a component. This is what I want to achieve. <input [(ngModel)]="Holiday" [dat ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Typescript issue: variable remains undefined even after being assigned a value in the constructor

In my code, I declared num1: number. constructor(){ ... this.num1 = 0; } This is all inside a class. However, when I try to log the value of this.num1 or typeof this.num1 inside a function using console.log(), it returns undefined in both cases. I ...

What steps can I take to troubleshoot why a pop-up window will appear in web Outlook but not in the 2016 version

While my dialog opens correctly in the Office web app, it only displays a loading indicator and shows "working on your request" in Office 2016. I've attempted to add a task pane, which successfully works and allows me to accept the HTTPS certificate o ...

Issues encountered when integrating ag-grid-react with typescript

Despite extensive searching, I am unable to find any examples of utilizing ag-grid-react with TypeScript. The ag-grid-react project does have TypeScript typing available. In my React app, I have installed ag-grid-react: npm i --save ag-grid ag-grid-react ...

Struggling to get Tailwind typography to play nice with a multi-column React application shell

I'm currently working on a React application with TypeScript and trying to integrate one of Tailwind's multi-column application shells (this specific one). I want to render some HTML content using Tailwind Typography by utilizing the prose class. ...

Create a new ASP.NET MVC project and integrate Angular 2 for a dynamic web application

I'm currently delving into the world of Angular 2 with Typescript. The primary resource I am using is QuickStart with Angular 2. From this and other examples, it has been emphasized to create a package.json file that outlines all dependencies for th ...

Having trouble showcasing the response data from a service in Angular onto the HTML view

I am facing an issue in my Angular2 application where I am trying to utilize a GitHub service to display returned data on the UI. Initially, I encountered an error stating "Cannot find a differ supporting object '[object Object]' of type 'o ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

What is an alternative way to confirm the invocation of a service method in Jasmine unit testing for Angular without relying on spyOn?

In my Angular project, I have a method named performAnalytics() within a service called analyticsService. This method is triggered when a specific element in the HTML is clicked. As part of writing unit test cases using Jasmine, I'm trying to ensure t ...

Tips for implementing md-icon in combination with md-autocomplete in Angular Material Design:

How can I include an md-icon in an md-autocomplete field? <md-autocomplete md-selected-item="ctrl.selectedItem" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-items="it ...

Show the navigation bar only when the user is logged in using Angular 6

Utilizing JWT for authentication, I have implemented a condition to display the navigation menu for logged-in users. <app-nav *ngIf="currentUser"></app-nav> <router-outlet></router-outlet> The issue arises after logging in when th ...

determine the appropriate month for the calendar month component based on the route selected

I have developed a calendar component where I want to preselect the default month based on the route parameters received for the component. Here is the calendar: <p-calendar [maxDate]="dateTime" [(ngModel)]="selectedMonth" name=&quo ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

Create a reusable React component in Typescript that can handle and display different types of data within the same

I have a requirement to display four different charts with varying data types. For instance, interface dataA{ name: string, amount: number } interface dataB{ title: string, amount: number } interface dataC{ author: string, amount: ...

What is the best location to store and import dependent SCSS files in Angular, Bootstrap 4, and angular-cli projects?

Check out this related question, especially useful if your SCSS code doesn't rely on Bootstrap's variables. In the index.html file: <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" However, when I t ...

By steering clear of using Route parameters such as (:id) in Angular, you can easily navigate

For our project, I am tasked with incorporating a navigation or redirect to a maintenance page if maintenance mode is turned on. Initially, I thought to handle this in the AuthGuard service with the following code snippet: canActivate(...) { if (this.i ...

Transitioning from AngularJS to Angular 2: Exploring Alternatives to $rootScope.$on

Our journey with the AngularJS project has begun on the path towards the modern Angular. The ngMigration utility advised me to eliminate all dependencies on $rootScope since Angular does not have a concept similar to $rootScope. While this is straightforw ...