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

Angular15/TS中如何统计数组元素出现次数并修复循环异常?

解决数组元素出现次数统计及Angular筛选列表生成问题

问题根源

你代码里的find回调函数没有返回判断结果,导致每次都找不到已存在的分类,所以会重复添加条目。原代码中:

const existingGenre = tempFilterList.find((entry) => {
  entry.name === photo.genre;
});

箭头函数使用大括号但未显式return,回调默认返回undefined,find永远匹配不到元素,自然每次都会执行push逻辑。

修复后的代码

只需在find回调里添加return,或者去掉大括号让箭头函数隐式返回:

方式1:添加return

setFilterList() {
  const tempFilterList: Genre[] = [];
  this.photos.forEach((photo) => {
    const existingGenre = tempFilterList.find((entry) => {
      return entry.name === photo.genre; // 补上return语句
    });
    if (existingGenre) {
      existingGenre.quantity += 1;
    } else {
      tempFilterList.push({
        name: photo.genre || 'generic',
        quantity: 1,
      });
    }
  });
  this.filterList = tempFilterList;
}

方式2:隐式返回(更简洁)

setFilterList() {
  const tempFilterList: Genre[] = [];
  this.photos.forEach((photo) => {
    const existingGenre = tempFilterList.find(entry => entry.name === photo.genre); // 去掉大括号,自动返回判断结果
    if (existingGenre) {
      existingGenre.quantity += 1;
    } else {
      tempFilterList.push({
        name: photo.genre || 'generic',
        quantity: 1,
      });
    }
  });
  this.filterList = tempFilterList;
}

更高效的实现方式(推荐)

可以用Array.reduce或者Map来统计,逻辑更清晰且性能更优:

使用reduce

setFilterList() {
  const genreMap = this.photos.reduce((map, photo) => {
    const genreName = photo.genre || 'generic';
    map.set(genreName, (map.get(genreName) || 0) + 1);
    return map;
  }, new Map<string, number>());

  this.filterList = Array.from(genreMap, ([name, quantity]) => ({ name, quantity }));
}

使用Map遍历

setFilterList() {
  const genreMap = new Map<string, number>();
  for (const photo of this.photos) {
    const genreName = photo.genre || 'generic';
    genreMap.set(genreName, (genreMap.get(genreName) || 0) + 1);
  }
  this.filterList = Array.from(genreMap, ([name, quantity]) => ({ name, quantity }));
}

这些方式不需要手动维护数组的查找逻辑,代码更简洁,也避免了类似的回调返回错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:47:35