Javascript: 检查匹配属性,箭头函数不会在 for 循环中更新 i

Javascript: Checking for matching properties, arrow function won't update i in for loop

我想检查一个对象 属性 是否存在于数组中,这样我就可以 assemble 一个唯一的 room 列表和一个 times(在这种情况下是一对字符串)。除了普通的数字数组之外,我还没有找到一种简洁的方法来为这个过程建模。

我试图遍历列表以检查我插入的列表是否已经包含匹配的 class 字段,不幸的是,变量 i 不会在我传递的函数中更新进入 findIndex()

const getClassroomList = (list) => {
  const temp = [{
    classroom: '',
    times: [{
      start_time: '',
      end_time: '',
    }],
  }];
  // For every classroom in list, check if classroom already exists.
  // If it does, add object to array
  // Else add pair of times to existing classroom
  for (let i = 0; i < list.length; i += 1) {
    const idx = list.findIndex((room) => {
      // console.log(i); Here the variable i won't update so the below fails
      return room.classroom === list[i].classroom;
    });
    if (idx === -1) {
      temp.push({
        classroom: list[i].classroom,
        times: [{
          start_time: list[i].start_time,
          end_time: list[i].end_time,
        }],
      });
    } else {
      temp[idx].times.push({
        start_time: list[i].start_time,
        end_time: list[i].end_time,
      });
    }
  }
  return temp;
};

似乎该函数使用它看到的 i 的第一个实例初始化自身,并在我希望它保持递增时将其保持在 0。我怎样才能实现这种行为?

我想我会在这里结束这个问题,因为我犯了一个愚蠢的小错误,在 list 上使用 findIndex() 而不是 temp

const idx = list.findIndex((room) => {
  return room.classroom === list[i].classroom;
});

固定摘录。

const idx = temp.findIndex(room => room.classroom === list[i].classroom);