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

JS数组元素属性自动变更:点击事件中currentRow固定为第四行

问题分析与修复

核心问题

  1. 遍历逻辑错误:getCurrentRow中使用map遍历数组,且在遍历过程中修改了后续元素的next属性。这会导致同一轮遍历中,后续元素的next被设为true后,再次触发if (row.next === true)的判断,进而重复执行赋值逻辑,最终currentRow被多次覆盖,固定为最后一个元素(row4)。
  2. 变量名错误:setRows函数中localStorage.setItem使用了未定义的rowsArr,应该是rowsArrT。

修复后的代码

let rowsArrT = [];
let currentRow;

const rowsEle = ['row1', 'row2', 'row3', 'row4'];

function setRows(rows) {
    rows.forEach((row, ind) => {
        rowsArrT.push({ row, id: ind, next: false, notes: 0 });
    });
    rowsArrT[0].next = true;
    localStorage.setItem('TestRows', JSON.stringify(rowsArrT)); // 修正变量名
}

function getCurrentRow() {
    // 找到当前next为true的元素索引,只处理一次
    const currentIndex = rowsArrT.findIndex(row => row.next === true);
    if (currentIndex === -1) return;
    
    currentRow = rowsArrT[currentIndex];
    // 重置当前元素的next
    rowsArrT[currentIndex].next = false;
    // 设置下一个元素的next
    const nextIndex = currentIndex === rowsArrT.length - 1 ? 0 : currentIndex + 1;
    rowsArrT[nextIndex].next = true;
}

setRows(rowsEle);

window.addEventListener('click', () => {
    getCurrentRow();
    console.log('-----After generate-----');
    console.log(currentRow);
    console.log(rowsArrT);
});

修复说明

  • 用findIndex替代map,直接定位到当前激活的元素索引,避免遍历过程中重复触发逻辑。
  • 修正localStorage中的变量名错误,确保存储的是正确的数组。
  • 逻辑更清晰:先找到当前项,再更新状态,每次点击只执行一次状态切换,保证currentRow依次切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:45:34