简体   繁体   English

JS 中的 console.log 与 return 的问题

[英]Issues with console.log vs. return in JS

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.我有以下 function 与 for 循环以及模板文字。 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.如果我使用 console.log,我会得到我期望的结果(发布在下面)但是如果我尝试返回它,我会得到 undefinedundefined 或 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.另外,我在这里写它的方式我无法从我的 return 语句中的 for 循环访问 [i]。 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这是我有 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.如果我删除这一行,我将不再收到"undefinedundefined"错误,所以我猜我在那里也做错了什么。 any help would be greatly appreciated!任何帮助将不胜感激!

for(n=0; n<this.tracks; n++){ // when this is removed the undefinedundefined error is no more. 

The incrementor i is scoped within that block of the for-loop which is why you cannot access it outside.增量器i的范围在 for 循环的该块内,这就是为什么您无法在外部访问它的原因。 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;
}

the loop should be for(n=0; n<this.tracks.length; n++){ I think you left out the length .循环应该是for(n=0; n<this.tracks.length; n++){我认为你遗漏了length And you need to define i the way you defined n .您需要按照定义n的方式定义i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM