如何正确实现JavaScript代码片段循环 解决仅返回i=0问题
问题根因
- 第一版代码把
return语句直接写在for循环体内部,JavaScript 执行到return会立即终止当前函数的运行,因此循环仅执行i=0的一次就直接返回结果退出,后续循环不会触发。 - 第二版代码存在两处错误:
- 外层
for循环内仍然内置return,同样会在第一次循环就退出整个函数 - 内层
for循环生成的<tr>字符串片段没有被拼接到最终的 table 返回字符串中,仅作为孤立字符串存在;同时内层循环判断条件误写为a.hre.length,多了冗余的字母e
- 外层
正确实现方案
核心逻辑:不要在循环内部直接返回结果,先把所有 table HTML 片段逐段拼接完成,再统一返回最终字符串。
thead 部分仅需生成一次,循环只负责拼接 tbody 内的所有数据行:
function format ( a ) { // 拼接 table 公共头部 + 开标签 let tableHtml = '<table cellpadding="5" cellspacing="0" border="0" class="table">'+ '<thead>'+ '<tr>'+ '<th data-sortable="true">Full name:</th>'+ '<th>Extension number:</th>'+ '<th>Extra info:</th>'+ '<th>Extra info:</th>'+ '</tr>'+ '</thead>'+ '<tbody>'; // 循环拼接所有数据行,此处禁止写 return for (let i = 0; i < a.hr.length; i++) { tableHtml += '<tr>'+ '<td>'+a.hr[i].position+'</td>'+ '<td>'+a.hr[i].salary+'</td>'+ '<td>'+a.hr[i].start_date+'</td>'+ '<td>'+a.hr[i].position+'</td>'+ '</tr>'; } // 拼接 table 闭合标签 tableHtml += '</tbody></table>'; // 所有内容拼接完成后再统一返回 return tableHtml; }
可选优化写法
使用 ES6 模板字符串 + 数组map方法,可读性更高:
function format ( a ) { // 批量生成所有数据行 const rowList = a.hr.map(item => ` <tr> <td>${item.position}</td> <td>${item.salary}</td> <td>${item.start_date}</td> <td>${item.position}</td> </tr> `).join(''); // 直接返回拼接完成的 table 字符串 return ` <table cellpadding="5" cellspacing="0" border="0" class="table"> <thead> <tr> <th data-sortable="true">Full name:</th> <th>Extension number:</th> <th>Extra info:</th> <th>Extra info:</th> </tr> </thead> <tbody>${rowList}</tbody> </table> `; }
内容的提问来源于stack exchange,提问作者Sallar Rabiei
相关产品推荐
相关产品推荐

