节点js + express + ejs.无法读取未定义的属性"option0" [英] node js + express + ejs. Cannot read property 'option0' of undefined

查看:96
本文介绍了节点js + express + ejs.无法读取未定义的属性"option0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app.js

var options = { option0: 11, option1: 'option1', option2: 'option2', option3: 'option3', option4: 'option4', option5: 'option5', option6: 'option6', option7: 'option7', option8: 'option8', option9: 'option9', option10: 'option10', }

res.render('main', {opt : options});

main.ejs

<select class="form-control" name="selected" required>

    <% for (let i = 1; i < opt.options.option0; i++) { %>
        <% optionName = 'option' + i %>
        <option value="<%= i %>"><%= opt.options[optionName] %></option>
    <% } %>

</select>

错误:无法读取未定义的属性'option0'.

ERROR: Cannot read property 'option0' of undefined.

推荐答案

您已通过 options 作为属性opt的引用对象,因此 opt 现在指向到 {option0:11,option1:'option1',...} ,并且您的渲染功能变为

You have passed the options as a reference object for the property opt.So opt will now point to { option0: 11, option1: 'option1', ...} and your render function becomes

res.render('main',{opt:{option0:11,option1:'option1',...}});

因此,当您尝试访问 opt.options.option0 时, opt.options 变得未定义并引发错误

So when you try to access opt.options.option0 , opt.options becomes undefined and throws error

因此,您应该使用`

<% for (let i in opt) { %>
    <% optionName = 'option' + i %>
    <option value="<%= i %>"><%= opt[i] %></option>
<% } %>

`

这篇关于节点js + express + ejs.无法读取未定义的属性"option0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆