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

Google App Script多维数组push报错:Cannot read properties of undefined (reading '0')

问题分析与修复方案

核心错误原因

你遇到的TypeError: Cannot read properties of undefined (reading '0'),是因为内层循环的终止条件写错了:

  • 你用了i < longitudvector+1,但longitudvector初始值是9,而vectorvalores一开始是空数组,当i超过vectorvalores的实际长度时,vectorvalores[i]就是undefined,访问[0]自然报错。
  • 还有个隐藏逻辑错误:else if(datos[j][0]='Venta')这里是赋值操作=,不是比较操作===,会导致所有非"Compra"的记录都被当成"Venta"处理。
  • 全局变量numeroaccionesa、averagepricea没有在每次处理新记录时重置,会导致不同股票的计算数据互相污染。

修复后的代码

function preciomedio(){
  var hojas = SpreadsheetApp.getActiveSpreadsheet();
  var situacioninversiones = hojas.getSheetByName('Situación de inversiones');
  var historicoinversiones = hojas.getSheetByName('Histórico Inversiones');
  var datos = historicoinversiones.getDataRange().getValues();
  var vectorvalores = [];
  var averageprice = 0;
  var numeroacciones = 0;

  for (var j=1;j<datos.length;j++){
    var estaba = false;
    var numeroaccionesa = 0;
    var averagepricea = 0;
    // 内层循环用vectorvalores的实际长度作为终止条件
    for(var i=0;i<vectorvalores.length;i++){
      if(datos[j][3] === vectorvalores[i][0]){
        // 取出当前已有的数据,避免全局变量污染
        numeroaccionesa = vectorvalores[i][1];
        averagepricea = vectorvalores[i][2];
        if(datos[j][0] === 'Compra'){
          numeroacciones = numeroaccionesa + datos[j][5];
          averageprice = (averagepricea * numeroaccionesa + datos[j][6]) / numeroacciones;
        } else if(datos[j][0] === 'Venta'){
          numeroacciones = numeroaccionesa - datos[j][5];
          // 卖出时平均价格不变,无需重新计算
          averageprice = averagepricea;
        }
        estaba = true;
        vectorvalores[i][1] = numeroacciones;
        vectorvalores[i][2] = averageprice;
        break; // 找到匹配项后跳出循环,减少无效遍历
      }
    }
    if(!estaba){
      var a = datos[j][3];
      var b = datos[j][5];
      var c = datos[j][6];
      var vector = [a,b,c];
      vectorvalores.push(vector);
      historicoinversiones.getRange(j+1,15).setValue(vector[0]); // 表格行从1开始,j从1计数需+1
    }
  }
}

关于用对象替代数组的问题

数组完全可以满足需求,修复后的代码就是用数组实现的。不过如果数据量很大,用Map或者普通对象会更高效:

  • 比如用Map的话,键是股票名称(datos[j][3]),值是包含持仓量和平均价格的数组/对象,查找时不用循环,直接map.get(股票名称)就能拿到数据,代码会更简洁。但当前阶段先让代码正常运行,之后再考虑优化即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:47