【问题标题】:node js + express + ejs. Cannot read property 'option0' of undefined节点js + express + ejs。无法读取未定义的属性“option0”
【发布时间】:2018-12-26 18:28:25
【问题描述】:

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”。

【问题讨论】:

  • opt is options 在页面被渲染时,所以opt.options 试图在opt 中找到不存在的optionsopt.option0 一个人就应该这样做(opt[optionName] 也是)。

标签: javascript html node.js express ejs


【解决方案1】:

您已将 options 作为属性 opt 的引用对象传递。所以 opt 现在将指向 { option0: 11, option1: 'option1', ...} 并且您的渲染函数变为

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

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

因此您应该使用 `

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

`

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2017-03-12
    • 2017-11-02
    • 2018-11-30
    • 2018-05-15
    • 2016-11-19
    相关资源
    最近更新 更多