TypeError:无法读取未定义的属性“ xx”

时间:2020-06-18 08:39:46

标签: javascript arrays google-apps-script google-sheets stripe-payments

我试图调用Stripe API以获得一些付款信息。代码如下:

function callStripe() { 
  var ss = SpreadsheetApp.openById("XXX");
  var sheet = ss.getSheetByName("XXX");
  var lastRow = sheet.getLastRow();
  var startRow = 1; // First row of data to process
  var dataRange = sheet.getRange(startRow, 1, sheet.getLastRow(), sheet.getLastColumn());
  var data = dataRange.getValues();

  for (var i = 0; i < lastRow + 1; ++i) {
    var row = data[i];
    var missedFee = row[6];

    if (missedFee == "") {  //only call for missing figures
       var txId = sheet.getRange(startRow + i, 2).getDisplayValue();
       var url = "https://api.stripe.com/v1/balance_transactions/" + txId;

       var params = {
        method: "GET",
        headers: {Authorization: "Basic " + Utilities.base64Encode("XXX:")}
        };
       var res = UrlFetchApp.fetch(url, params);
       var transaction = JSON.parse(res);


         var fee = transaction["fee"];
         var net = transaction["net"];
         sheet.getRange(startRow + i, 7).setValue(fee / 100);
         sheet.getRange(startRow + i, 9).setValue(net / 100);}
  }}

运行该函数后,我可以从API中获得所需的信息,但是出现以下错误:

TypeError: Cannot read property '6' of undefined (line 112, file "Code")

第112行指的是

var missedFee = row[6];

我可以知道做错了什么吗?

1 个答案:

答案 0 :(得分:1)

您定义了循环for (var i = 0; i < lastRow + 1; ++i)

鉴于您以0开头(这是正确的,因为第一个数组项是0),最后一个i应该是lastRow-1

示例:

  • 让我们说您有三行,然后您要迭代三遍
  • 您的行将是data[0]data[1]data[2]
  • 现在,如果您将i < lastRow + 1定义为执行循环的条件,则它也将为i = 3执行
  • 但是没有data[3](那是第四行),因此,第4行(var missedFee = row[6];)中没有第7列
  • 这就是给您带来错误的原因