How to create getter function with for loop in this class?

Viewed 20

Using Typsescript here. I was able to set up a getter function to return all the values in the kids array but can anyone tell me how to create a getKid function in the class that allows me to put in the index and return the name of the kid associated with that particular index in the kids array?

class Player3 {
   kids: string[] = [];
  // private health: number;
  // private speed: number;

  constructor(public name: string, private health: number, public speed: number) {
    // this.health = h;
    // this.speed = s;
  }

  getHealth() {
    console.log(this.health);
  }

  setKid(kid: string) {
    this.kids.push(kid);
  }

  getKids() {
    for(let i =0; i < this.kids.length; i++) {
      console.log(this.kids[i])
    }
  }  
}
1 Answers
class Player3 {
   kids: string[] = [];
  // private health: number;
  // private speed: number;

  constructor(public name: string, private health: number, public speed: number) {
    // this.health = h;
    // this.speed = s;
  }

  getHealth() {
    console.log(this.health);
  }

  setKid(kid: string) {
    this.kids.push(kid);
  }

  getKids() {
    for(let i =0; i < this.kids.length; i++) {
      console.log(this.kids[i])
    }
  }  

  getKidAtIndex(i: number){
    console.log(this.kids[i]);
  }
}

let p = new Player3("pepe", 1, 1);
p.setKid("jota");
p.setKid("Carlos");
p.getKids();
p.getKidAtIndex(1);

In itself it is the same logic that you implemented previously in getKids

You can also place restrictions so that the size of the array is not exceeded..

Related