【问题标题】:Google Apps Script - TypeError: Cannot read property "0" from undefinedGoogle Apps 脚本 - 类型错误:无法从未定义中读取属性“0”
【发布时间】:2014-05-04 08:38:18
【问题描述】:

我在这行代码中不断收到“未定义错误”:

      while (agentSheetValues[j][0] != "") {

...即使我使用 Logger.log(agentSheetValues[j][0]) 它输出变量,所以我知道它已定义。我也尝试用 for 循环替换 while 循环并遇到同样的问题;怎么回事?

完整代码如下,谢谢。

  var resultSS = SpreadsheetApp.openById('someKey');
  var agentSheet = resultSS.getSheetByName('Agents');
  var agentSheetRows = agentSheet.getDataRange();
  var agentSheetValues = agentSheetRows.getValues();

  var agentSheets = [];

  var j = 1;

  while (agentSheetValues[j][0] != "") {
    var sheetKey = agentSheetValues[j][1];
    agentSheets.push(sheetKey);
    j++
  }

【问题讨论】:

  • var j = 1 之后添加行:console.log(agentSheetValues) 并确保该数组不为空或为空。

标签: javascript google-apps-script


【解决方案1】:

您应该在循环中考虑到您的数据数组可能会在您达到空值之前结束。试试这个:

var resultSS = SpreadsheetApp.openById('someKey');
var agentSheet = resultSS.getSheetByName('Agents');
//getDataRange returns from A1 to the last column and row WITH DATA.
//you'll not get the whole sheet. Blank rows and columns after the end are ignored
var agentSheetDataRange = agentSheet.getDataRange();
var data = agentSheetDataRange.getValues();

var agentSheets = [];
//I'm assuming you started 'j = 1' on purpose, to skip the header row
//Also, if you're sure you do not have another column with more data than A
// you could drop the::  && data[j][0] != ''
for( var j = 1; j < data.length && data[j][0] != ''; ++j )
  agentSheets.push(data[j][1]);

【讨论】:

  • 非常感谢恩里克。实际上,我已经从“while”切换到“for”,这解决了问题,但感谢您解释为什么我的“while”不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
相关资源
最近更新 更多