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

在Google Apps Script中创建动态字典统计列值出现次数

解决Google Sheets列值统计为字典的问题

你的函数返回undefined的核心问题是循环边界错误:
原循环条件 i<=col_values.length 会让循环执行到 i = col_values.length,此时col_values[i]是undefined,访问col_values[i][0]会触发报错,导致函数异常终止返回undefined。

以下是两种符合需求的实现方案:

方案1:使用普通JS对象(对应Python字典结构)

function count_occurances_in_col(col_values){
  let occurances_dict = {};
  // 修正循环条件:遍历所有有效元素
  for(let i = 0; i < col_values.length; i++){
    const key = col_values[i][0];
    if(occurances_dict[key]){
      occurances_dict[key] += 1;
    } else {
      occurances_dict[key] = 1;
    }
  }
  return occurances_dict;
};

方案2:修正Map写法(若需使用Map)

如果坚持使用Map,仅需修正循环边界即可:

function count_occurances_in_col(col_values){
  let occurances_dict = new Map();
  for(let i = 0; i < col_values.length; i++){
    const key = col_values[i][0];
    if(occurances_dict.has(key)){
      occurances_dict.set(key, occurances_dict.get(key) + 1);
    } else {
      occurances_dict.set(key, 1);
    }
  }
  return occurances_dict;
};

若需将Map转换为普通对象,可在返回时使用return Object.fromEntries(occurances_dict);。

效果验证

当输入col_values = [["A"], ["A"], ["A"], ["B"], ["B"], ["C"]]时,函数会返回:

{ A: 3, B: 2, C: 1 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:17:36