-1

I'm running into some issues here and I was hoping to get some help. I have the following function with a for loop as well as a template literal. If I use console.log I am getting the results I expect (posted below) however If I try to return it, i get undefinedundefined or object Object. also, the way i have it written here I don't have access to [i] from the for loop within my return statement. Can anyone give me some pointers here?

renderPlaylistCard() {
  for (let i = 0; i < this.tracks.length; i++) {
    console.log(this.name, this.tracks[i].title, this.tracks[i].artist)
  }
  let n;
  for (n = 0; n < this.tracks; n++) {
    console.log(this.name, this.tracks[n].title, this.tracks[n].artist)
  }
  return `            
      <div data-id=${this.id}>
      <h4><li>Playlist Name: ${this.name}</h4></li> 
      <h4><li>Title: ${this.tracks[i].title}</h4></li> 
      <h4><li>Artist: ${this.tracks[i].artist}</h4></li> 

     </div> </li>
      `
}
}

Here is the expected result that I have console.logged

 Country Songs Fourth Song Kristy
 Country Songs First Song Randy
 Pop Songs Third Song Brady
 Pop Songs Hip Hop Horray Randy
 Pop Songs Second Song Kristy

And if i remove this line, I no longer get the "undefinedundefined" error so I'm guessing I'm doing something wrong there as well. any help would be greatly appreciated!

for(n=0; n<this.tracks; n++){ // when this is removed the undefinedundefined error is no more. 
Phil
  • 157,677
  • 23
  • 242
  • 245
Randy
  • 1
  • 3

2 Answers2

0

The incrementor i is scoped within that block of the for-loop which is why you cannot access it outside. I believe what you're trying to do can be accomplished with the following:

renderPlaylistCard() {
  let output = "";

  for(let i=0; i < this.tracks.length; i++){
    output += `
    <div data-id=${this.id}>
      <h4><li>Playlist Name: ${this.name}</h4></li> 
      <h4><li>Title: ${this.tracks[i].title}</h4></li> 
      <h4><li>Artist: ${this.tracks[i].artist}</h4></li> 
    </div>`;
  }

  return output;
}
Bren
  • 605
  • 4
  • 15
0

the loop should be for(n=0; n<this.tracks.length; n++){ I think you left out the length. And you need to define i the way you defined n.

Anne
  • 159
  • 7