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

如何将获取的JSON数组索引作为桌号显示在表格中?

解决方法:将数组索引作为桌号显示

嘿,我明白你的需求啦——你希望把每个JSON数组项的索引作为桌号(按日常习惯从1开始计数)显示在表格第一列,而不是固定的"Table"文本对吧?其实调整起来很简单,只要利用forEach方法的第二个参数就能轻松拿到元素的索引。

修改后的完整代码

function getExternal() { 
  fetch('https://kyoala-api-dev.firebaseapp.com/queue-group/5e866db4-65f6-4ef0-af62-b6944ff029e5') 
    .then(res => res.json()) 
    .then((res) => { 
      let reservationList = ''; 
      // forEach支持传入第二个参数:当前元素在数组中的索引(默认从0开始)
      res.forEach(function (reservation, index) { 
        reservationList += ` 
        <tr> 
          <th scope="row">${index + 1}</th> <!-- 索引+1,让桌号从1开始计数 -->
          <td class="text-center">${reservation.minCapacity} - ${reservation.maxCapacity}</td> 
          <td class="text-center">${reservation.activeQueuesCount}</td> 
        </tr>`; 
      }); 
      document.getElementById('lists').innerHTML = reservationList; 
    }) 
    .catch(err => console.log(err)); 
};

关键调整说明

  • forEach的第二个参数index就是当前元素在数组里的位置,默认从0开始;
  • 给索引加1(index + 1)是为了贴合日常桌号从1开始的计数习惯,如果你需要保留0开头的索引,直接用index即可;
  • 把原来固定的<th scope="row">Table</th>替换成动态计算的索引值,就能实现你想要的桌号显示效果啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:48:23