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

如何统计map循环次数,为表格第一行的<td>设置加粗样式?

实现方法

JS 数组的 map 方法回调支持第二个参数,为当前遍历元素的索引(从0开始计数),第一行对应的索引为0,你可以基于这个判断添加加粗样式,不需要逐个给td加样式,直接给行设置样式即可统一生效:

<table>
  ...
  {categories.map((val, index) => (
    <tr style={index === 0 ? {fontWeight: 'bold'} : {}}>
      <td>{val.name}</td>
      <td>{val.formula}</td>
      <td>{val.values[0].value.toLocaleString()}</td>
      <td>{val.values[1].value.toLocaleString()}</td>
      <td>{val.description}</td>
    </tr>
  ))}
</table>

如果你只需要给第一行的部分单元格加粗,单独给对应td加判断即可:

<td style={index === 0 ? {fontWeight: 'bold'} : {}}>{val.name}</td>

语义化优化方案

从HTML语义化和无障碍访问的角度,表头行的单元格建议用<th>标签代替<td>,本身自带加粗样式,也更符合规范:

<table>
  ...
  {categories.map((val, index) => {
    const Cell = index === 0 ? 'th' : 'td'
    return (
      <tr>
        <Cell>{val.name}</Cell>
        <Cell>{val.formula}</Cell>
        <Cell>{val.values[0].value.toLocaleString()}</Cell>
        <Cell>{val.values[1].value.toLocaleString()}</Cell>
        <Cell>{val.description}</Cell>
      </tr>
    )
  })}
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:06:02