Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 嵌套循环函数_Javascript_Mongoose - Fatal编程技术网

Javascript 嵌套循环函数

Javascript 嵌套循环函数,javascript,mongoose,Javascript,Mongoose,我很难理解嵌套for循环 posts: [ { title: 'lorem', comments: [ { content: 'lorem' user: 'John' }, ... ] }, ... ] 我的目标是在所有帖子中获得特定用户的所有评论。 下面是我如何继续的(我使用mongoose,我从auth中间件获取用户) const postsList=wait Post.find(

我很难理解嵌套for循环

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

  ...
]
我的目标是在所有帖子中获得特定用户的所有评论。 下面是我如何继续的(我使用mongoose,我从auth中间件获取用户)

const postsList=wait Post.find();
var userComments=[];
对于(变量i=0;i0){
对于(var j=0;j

当我尝试此操作时,我得到一个
无法读取未定义的属性“length”
。我想我的错误在第二个for循环中,但我不知道为什么。需要帮忙吗

评论中的Mark Meyer是正确的

comments
是每个
post
对象内部的一个数组<代码>注释[j]
将引用注释数组中的元素
comments[j]。length
没有意义,因为要运行嵌套的
j
for循环(该循环迭代
comments
数组),您需要的是
comments
数组的长度,而不是其中一个元素的长度

下面是需要修复的行:

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++)
       // fixed version below
        for (var j = 0; j < postsList[i].comments.length; i++)


          if (postsList[i].comments[j].user == req.user.id) {
            userComments.push(comments[j]);
          }
      }
 }
const postsList=wait Post.find();
var userComments=[];
对于(变量i=0;i0){
//对于(var j=0;j
可能应该是
postsList[i].comments.length
而不带
[j]
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++)
       // fixed version below
        for (var j = 0; j < postsList[i].comments.length; i++)


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