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

如何在JavaScript forEach循环中获取遍历对象的索引?

问题解决

forEach获取遍历索引的方法

Array.prototype.forEach的回调函数默认按顺序接收三个参数:

  • 当前遍历到的数组元素
  • 当前元素对应的索引(从0开始计数)
  • 正在遍历的原数组本身
    你只需要在回调的参数列表里声明第二个参数,就能直接拿到当前遍历对象的索引,不需要额外定义计数变量。

代码修正说明

你原有代码渲染异常有两个核心问题:

  • 没有接收遍历索引,直接把整个data对象作为left定位值,对象转字符串后是无效的样式值
  • 直接用索引作为left值如果没有做比例换算,数据量多的时候会出现点溢出图表容器的情况

修正后的可运行代码:

async function getBatteryset() {
    let url = '/getBatLevel.php';
    try {
        let res = await fetch(url);
        return await res.json();
    } catch (error) {
        console.log(error);
    }
}
async function renderBattData() {
    let dataset = await getBatteryset();
    // 图表可用绘制宽度,和你设置的--widget-size尺寸匹配即可
    const chartDrawWidth = 600;
    let html = '<figure class="css-chart" style="--widget-size:650px;"><ul class="line-chart">';
    // 回调第二个参数index就是当前项的索引
    dataset.forEach((data, index) => {
        // 等比计算left值,预留边距避免首尾点贴边
        let leftPosition = (chartDrawWidth / (dataset.length - 1)) * index;
        let htmlSegment = `<li>
                            <div class="data-point" data-value=${data.ID} style="bottom: ${data.BatV*100}px; left: ${leftPosition}px"></div>
                        </li>`;
        html += htmlSegment;
    });
    html += '</ul></figure>'
    let container = document.querySelector('.BattChart');
    container.innerHTML = html;
}

提示:如果你的BatV取值范围不是0-1区间,直接乘100作为bottom定位值会出现点超出图表上下边界的问题,可以根据你实际采集的电压量程做等比缩放调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:22:20