首页 > 解决方案 > 为什么在 pug 模板中迭代时出现“无法读取未定义的属性‘长度’”错误?

问题描述

我正在用 Node 和 Express 构建一些东西,如果用户没有登录,那么主页应该在导航栏中显示注册和登录链接。一切看起来应该可以工作,如果我不迭代,我可以显示信息。但是当我使用迭代时,我得到了这个错误:

/home/michael/Desktop/budget-app/views/layout.pug:13 11| a(href='/') Simple Money Manager 12| if authLinks > 13| each val, index in authlinks 14| a(href='' + val) index 15| 16| // Content Cannot read property 'length' of undefined

这是render方法:

res.render('home', {
   authLinks: {
      Signup: "/signup",
      Login: "/login"
   }
});

这是我的 pug 文件中使用的代码:

if authLinks
    each val, index in authlinks 
      a(href='' + val) index

为什么 authLinks 未定义?我完全不知所措。谢谢您的帮助。

标签: javascriptnode.jsexpresspug

解决方案


它应该在authLinks而不是authlinks在循环中

if authLinks
    each val, index in authLinks//here 
      a(href='' + val) index  

编辑:您的 authLinks 是一个对象,而不是一个数组,也不能重复:

res.render('home', {
   authLinks: [{
      Signup: "/signup",
      Login: "/login"
   }]
});

推荐阅读