嵌套用于循环功能

时间:2019-06-23 15:09:37

标签: javascript mongoose

我难以理解嵌套的循环

posts: [
  {
    title: 'lorem',
    comments: [
      {
         content: 'lorem'
         user: 'John'
      },
      ...
    ]
  },

  ...
]

我的目标是在所有帖子中获得特定用户的所有评论。 这是我的工作方式(我正在使用猫鼬,我从授权中间件获取用户)

const postsList = await Post.find();
var userComments = [];

 for (var i = 0; i < postsList.length; i++) {

     if (postsList[i].comments.length > 0) {

        for (var j = 0; j < postsList[i].comments[j].length; i++)

          if (postsList[i].comments[j].user == req.user.id) {
            userComments.push(comments[j]);
          }
      }
 }

尝试此操作时,我得到一个Cannot read property 'length' of undefined。我认为我的错误是在第二个for循环中,但我不明白为什么。有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

评论中的Meyer是正确的。

Private Sub CommandButton1_Click() ' Objetos Word Dim obj1 As New Application Dim wdDoc As Word.Document ' Objetos Excel Dim wbBook As Workbook Dim wsSheet As Worksheet Dim Caminho, Arquivo, Nome_aluno, Ender As String Dim Gen_p, Gen_a, Hora, Prof, Resp As String Dim i, Comp As Integer Dim Coord_C As Integer Dim Coord_L As Integer Caminho = "D:\Data\Office\Excel\" Arquivo = "Anexo D - Ata de defesa TCC.docx" 是每个comments对象内部的数组。 post将引用注释数组中的元素。 comments[j]没有意义,因为为了运行嵌套的comments[j].length for循环(在j数组上进行迭代),您需要comments数组的长度,而不是长度其元素之一的长度。

这是需要修复的行:

comments