You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在客户端正确遍历EJS数组?解决属性未定义报错

问题原因

EJS是服务器端渲染引擎,服务器处理模板时会优先解析所有<%= %>标签内的代码,而你写的for循环是客户端浏览器运行的JS逻辑。当服务器渲染模板时,客户端变量i还未被定义,此时subs[0].questions[i]等价于subs[0].questions[undefined],自然会抛出Cannot read property 'optn_type' of undefined的错误。

可行解决方案

方案1:用EJS循环语法在服务器端生成客户端代码

直接借助EJS的遍历能力,在服务器端提前把questions数组的optn_type渲染到客户端JS中:

<script>
// 先通过EJS遍历生成客户端可用的类型数组
const questionTypes = [
  <% subs[0].questions.forEach((ques, idx) => { %>
    "<%= ques.optn_type %>"<%= idx !== subs[0].questions.length - 1 ? ',' : '' %>
  <% }) %>
];

// 客户端正常遍历数组
for(let i = 0; i < questionTypes.length; i++) {
  const type = questionTypes[i];
  console.log(type);
}
</script>

方案2:将questions序列化为JSON传递到客户端

把整个questions数组转成JSON字符串,渲染到客户端后解析为JS对象,再自由遍历:

<script>
// 服务器端把数组转成JSON字符串,客户端解析后使用
const questions = JSON.parse('<%= JSON.stringify(subs[0].questions) %>');

// 客户端正常遍历操作
for(let i = 0; i < questions.length; i++) {
  const type = questions[i].optn_type;
  console.log(type);
}
</script>

注:JSON.stringify会自动转义特殊字符,避免客户端JS出现语法错误。

内容的提问来源于stack exchange,提问作者Viraj Doshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:12:55