【问题标题】:How to display array inside another array without them multiplying?如何在不相乘的情况下在另一个数组中显示数组?
【发布时间】:2018-02-26 05:52:27
【问题描述】:

所以我有这个应用程序,我需要在其中显示上传到我的 MongoDB 数据库的图像。我可能能够显示它们,但我想通过环绕显示的每个图像的链接来更进一步。该链接将包含每个图像的id,用户可以单击该链接并获取有关图像的更多信息。

所以这就是问题的开始。我必须使用另一种方法来显示这些图像周围的链接包装器。因此,每当我使用数组显示链接时,图像都会乘以 3。如果我的数据库中有 3 张图像,当我使用数组显示链接包装器时,将同时显示另外 6 张图像。

让我提供更多上下文。

这些是没有链接包装显示的图像:

这是我用来显示这 5 张图片的代码。

app.get('/', function (req, res) {meme.find({}, {}, function (err, result) {            
  if (err) throw err; 
  res.render('pages/index', {
    user: req.user,
    path: result.map(u=> u.imgs),   
    Title: 'The Meme Search Engine - Meme Africa'
  });
 });
}); 

用于显示这些图像的前端。

<div class="container-fluid">
  <div class="row">         
    <% for(var i=0; i<path.length; i++) { %>
      <div class="col-md-1 col-md-offset-1">
        <img src='http://localhost:5000/public/Images/<%= path[i] %>' style="height: 150px; width: 150px; line-height: 0px" alt="memes">
      </div>
    <% } %>
  </div>  
</div> 

现在我想为每张图片加上链接,以便用户可以点击它们以获取有关每张图片的更多信息。这将需要另一个数组。

这就是我的代码的样子:

app.get('/', function (req, res) {
  meme.find({}, {}, function (err, result) {            
    if (err) throw err; 

    res.render('pages/index', {
      user: req.user,
      pathi: result.map(i => i.username),
      path: result.map(u=> u.imgs),     
      Title: 'The Meme Search Engine - Meme Africa'
    });
  });
}); 

前端代码如下:

<div class="container-fluid">
  <div class="row">         
    <%  for (var x=0; x<pathi.length; x++) {%>
      <% for(var i=0; i<path.length; i++) { %>
        <div class="col-md-1 col-md-offset-1">
          <a href="/Images/<%= pathi[x]%>">
            <img src='http://localhost:5000/public/Images/<%= path[x] %>' style="height: 150px; width: 150px; line-height: 0px" alt="memes">  
          </a>
        </div>
      <% } %>
    <%}%>
  </div>  
</div>  

结果:

您可以看到所有图像都成倍增加。同时,我的 MongoDB 数据库中只有 5 张图像。我认为问题在于使用数组来显示链接换行。现在我很好奇在没有我的初始结果成倍增加的情况下最好的方法是什么。

很抱歉这个冗长的答案,因为这个问题看起来有点复杂,我需要向有兴趣帮助我解决的人提供一切。如果您想让我澄清任何事情,请不要犹豫,在评论部分告诉我。

我正在使用的堆栈:Node/express、ejs 作为模板和 MongoDB。

谢谢。

【问题讨论】:

  • 你从 mongodb 查询中得到什么,请添加响应也形成查找查询。

标签: javascript arrays node.js mongodb express


【解决方案1】:

由于您只使用x 索引,因此您只需要一个循环(并且只获得一次模因迭代):

<div class="container-fluid">
<div class="row">           

<%  for (var x=0; x<pathi.length; x++) {%>

            <div class="col-md-1 col-md-offset-1">
<a href="/Images/<%= pathi[x]%>"> <img src='http://localhost:5000/public/Images/<%= path[x] %>' style="height: 150px; width: 150px; line-height: 0px"  alt="memes">  </a>
</div>

  <% } %>
 <%}%>

</div>  
</div> 

或者您可以将所有信息作为对象数组传递并从一个数组中读取属性。

【讨论】:

  • 如何将所有信息作为对象数组传递并从一个数组中读取属性?
  • Nvm。这些东西现在正在工作。你的回答有帮助。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-12-27
  • 2023-02-05
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
相关资源
最近更新 更多