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

JavaScript对象遍历仅输出2行问题排查及正确遍历方案咨询

问题原因

你出现的问题核心是遍历对象错误:

  • 你代码中for(let corso in corsiArrayAll)遍历的是外层corsiArrayAll对象,从控制台打印可知这个对象只有utente、corsi两个可枚举属性,所以循环只会执行2次,并非循环提前终止。
  • 额外小问题:表头代码里<th scope='col>Numero Persone</th>缺少scope属性的闭合单引号,可能导致表格渲染异常;且表格字段对应错误,第三列表头是“人数”,你当前代码填充的是课程开始时间字段。

正确遍历方式

直接遍历corsiArrayAll.corsi数组即可,推荐使用数组的forEach方法或者for...of循环,修改后的核心代码如下:

success: function(result) {
    $("div#spinner-border").slideToggle();
    var corsiArrayAll = JSON.parse(result);
    console.log(corsiArrayAll);

    // 修复表头的引号问题
    $('table#corsi-table').append(
        "<thead><tr>"+
        "<th scope='col'>Nome</th>"+
        "<th scope='col'>Nome Corso</th>"+
        "<th scope='col'>Numero Persone</th>"+
        "<th scope='col'>Data inizio corso</th>"+
        "<th scope='col'>Data fine corso</th>"+
        "<th scope='col'>Orario inizio corso</th>"+
        "<th scope='col'>Orario fine corso</th></tr></thead>"
    );

    // 直接遍历corsi数组,不需要额外声明index变量
    corsiArrayAll.corsi.forEach(function(corso) {
        $('table#corsi-table').append(
            "<tbody><tr>"+
            "<td>"+corsiArrayAll.utente.name+"</td>"+
            "<td>"+corso.nome+"</td>"+
            // 修复字段对应,人数用membriMax字段
            "<td>"+corso.membriMax+"</td>"+
            "<td>"+corso.inizio+"</td>"+
            "<td>"+corso.fine+"</td>"+
            "<td>"+corso.orario_inizio+"</td>"+
            "<td>"+corso.orario_fine+"</td>"+
            "</tr></tbody>"
        );
    });
},

如果偏好for循环写法,也可以用:

for(let i = 0; i < corsiArrayAll.corsi.length; i++){
    const corso = corsiArrayAll.corsi[i];
    // 渲染逻辑和上面一致
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:09:00