可能是因为total的值没有被正确更新。在每次累加cur.type的数量时,需要同时更新total的值,但是代码中只在第一次设置total的值,之后没有更新。可能的解决方法是,在每次累加cur.type的数量后,再次遍历acc[cur.name]的属性,累加所有类型的数量,更新total的值。具体代码如下:

arr.reduce((acc, cur) => {
  if (cur.name in acc) {
    if (cur.type in acc[cur.name]) {
      acc[cur.name][cur.type]++;
    } else {
      acc[cur.name][cur.type] = 1;
    }
  } else {
    acc[cur.name] = {};
    acc[cur.name][cur.type] = 1;
  }
    
  if(!acc[cur.name].total){
    acc[cur.name].total = 0
  }
  
  acc[cur.name].total = 0;
  for(let type in acc[cur.name]){
    if(type !== 'total'){
      acc[cur.name].total += acc[cur.name][type];
    }
  }
     
  return acc;
}, result);
arrreduceacc cur = if curname in acc if curtype in acccurname acccurnamecurtype++; else acccurnamecurtype = 1; else acccurname = ; acccurnamecurtype = 1; if!

原文地址: https://www.cveoy.top/t/topic/Ycf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录