
本文讲解如何正确遍历嵌套在对象中的数组(如 section1),并安全、准确地提取每个子对象的 title 和 content 字段,生成结构化 HTML 卡片(),避免常见属性访问错误。
本文讲解如何正确遍历嵌套在对象中的数组(如 `section1`),并安全、准确地提取每个子对象的 `title` 和 `content` 字段,生成结构化 html 卡片(`
在前端开发中,常需将嵌套数据结构(如对象内含数组,数组中又含多个对象)动态渲染为 DOM 元素。示例数据如下:
const data = {
type: 'main',
section1: [
{ title: 'title_one', content: 'cont_1' },
{ title: 'title_two', content: 'cont_2' }
]
};
目标是为 section1 中的每一项生成一个
标题和(可选)正文内容。
原始代码存在关键错误:
function main(content) {
const html = content.section1.map((item, index) => `
<div class="card">
<h1>${content.title[index]}</h1> <!-- ❌ 错误:content 没有 title 数组 -->
</div>
`);
return `
<main><section>${html.join('')}</section></main>
`;
}
问题在于:content.title[index] 尝试访问 content.title(即顶层对象的 title 属性),但实际 title 是 section1 数组中每个元素的自有属性。正确路径应为 item.title(推荐)或 content.section1[index].title(按原答案修正)。
✅ 推荐写法(语义清晰、无需索引依赖):
function main(content) {
const html = content.section1.map(item => `
<div class="card">
<h1>${item.title}</h1>
<p>${item.content}</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5493" title="html-to-pptx"><img
src="https://img.php.cn/upload/skill/000/000/081/179051045119472.jpg" alt="html-to-pptx" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5493" title="html-to-pptx" class="overflowclass">html-to-pptx</a>
<p class="overflowclass">将多页 HTML 演示文稿转换为美化的 PPTX 文件,便于分享和分发。</p>
</div>
<a rel="nofollow" href="/xiazai/skill5493" title="html-to-pptx" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
</div>
`).join('');
return `
<main><section>${html}</section></main>
`;
}
? 注意事项:
- 始终使用 map() 的回调参数 item 直接访问当前对象属性,比依赖 index 更安全、更易读;
- 若需兼容旧环境或显式强调索引逻辑,可改用 content.section1[index].title,但不推荐冗余写法;
- 实际项目中建议对 item.title 和 item.content 做空值校验(如 item.title ?? '无标题'),防止模板注入 undefined;
- 返回的 HTML 字符串应确保闭合标签完整,避免 DOM 解析异常。
调用示例:
console.log(main(data)); // 输出: // <main> // <section> // <div class="card"> <h1>title_one</h1> <p>cont_1</p> </div> // <div class="card"> <h1>title_two</h1> <p>cont_2</p> </div> // </section> // </main>
掌握这种嵌套数据的遍历与插值模式,是构建动态组件(如卡片列表、文章摘要区)的基础能力。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










