-2

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])
    }
  }  
}
Blockpain
  • 17
  • 3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 19 '22 at 12:14

1 Answers1

0
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..

  • Thank you. There is also a type of for loop that is "for in" or "for of" that would be an alternative way to write this that I'm trying to figure out but haven't had much luck. I tried the following but it did not work. getKidAtIndex3(k: number) { for(k in this.kids){ console.log(this.kids[k]) } } – Blockpain Sep 18 '22 at 16:42
  • if you need 3th kid you use p.getKidAtIndex(2) you no need to make function for every index – Danilo Mercado Oudalova Sep 18 '22 at 16:45
  • Gotcha. No i meant there is a shortcut way to write a for loop called where you say "for in kids." or "for of kids.length" or something like that that i was curious about how to write but the other way works fine so no big deal. – Blockpain Sep 18 '22 at 16:48
  • let num = [7, 8, 9]; num.forEach(function (value) { console.log(value); }); – Danilo Mercado Oudalova Sep 18 '22 at 16:52