【问题标题】:object key is not defined javascript/ejs [duplicate]对象键未定义javascript/ejs [重复]
【发布时间】:2021-10-01 20:50:06
【问题描述】:

我有一个名为 posts 的数组,它包含一个对象:

var posts = []

app.get('/', function(req, res) {
    res.render('home', {
        homestct: homeStartingContent,
        posts: posts
    })
})

app.post('/compose', function(req, res) {
    const comp = {
        title: req.body.compTitle,
        post: req.body.compPost
    }
    posts.push(comp)
    res.redirect('/')

})

当我尝试检索密钥时:title in home.ejs =

    <% for (var i = 0; i <= posts.length; i++) { %>
        <% console.log(posts[i].title) %>
            <% } %>

它给了我错误:无法读取未定义的属性“标题”

请帮忙T_T

【问题讨论】:

    标签: javascript node.js arrays javascript-objects ejs


    【解决方案1】:
    <% for (var i = 0; i < posts.length; i++) { %>
    

    i 应小于 posts.length。将&lt;= 替换为&lt;

    【讨论】:

      【解决方案2】:

      你的错误是你有&lt;= 而不是&lt;。让我来说明原因。

      假设您的帖子数组如下所示:

      [
        { title: 'A', post: 'a' }, // This will be posts[0]
        { title: 'B', post: 'b' }  // This will be posts[1]
      ]
      

      您有两个帖子,所以posts.length 将是2。第一个帖子是posts[0],第二个帖子是posts[1]

      既然你做了for (var i = 0; i &lt;= posts.length; i++),这意味着你的循环只会在i &lt;= posts.length不再为真时停止,这意味着如果i &lt;= 2不再为真,即当i达到3时,循环将停止, 但它将针对012 执行。

      您可能会注意到,现在这意味着访问 三个 索引(012)尽管您的数组中只有 两个 个帖子(带有索引01)!

      在第三次迭代中,您访问的是posts[2],即undefined。这意味着读取posts[2].title 的尝试失败,因为它实际上尝试读取undefined.title,这是不可能的,因此出现错误Cannot read property 'title' of undefined

      底线:当你有一个从零开始的索引(以0 开始)并且你有元素总数作为限制器(例如来自.length)时,你总是需要使用&lt; 而不是&lt;= 以确保您停止一个短于长度的索引,因为最后一个索引将始终是 length - 1

      建议:您可以使用for ... of 遍历元素本身,而不是乱用索引:

          <% for (const post of posts) { %>
              <% console.log(post.title) %>
          <% } %>
      

      【讨论】:

      • 非常感谢
      猜你喜欢
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2018-04-08
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      相关资源
      最近更新 更多