在 AppsScript 中尝试从二维数组中提取字符串时出现类型错误

问题描述 投票:0回答:0

我正在尝试编写一个程序,它将遍历 Google 表格文件 (Sheet1) 中几列中的每个单元格,并将这些单元格中的值与不同 Google 表格文件 (Sheet2) 中其他列中的值进行比较。如果可以在 Sheet2 中找到 Sheet1 中的单元格值,脚本将从 Sheet1 中删除具有该值的行。我正在使用

.getRange()
函数来获取每列中所有值的二维数组。问题是,当我尝试从二维数组中的每个单独数组中提取字符串值时,它给了我这个错误:

TypeError: Cannot read properties of undefined (reading 'length')

这是我试过的代码:

function CheckDNCList(string){
  id = 'SHEET2_ID'
  var ss = SpreadsheetApp.openById(id)
  SpreadsheetApp.setActiveSpreadsheet(ss)
  var sheet = ss.getSheets()[0];
  var num_rows = sheet.getLastRow().toString();
  var num_rows = num_rows.replace(".0","");
  var ret_val = false
  for (var i = 1; i < 3; i++){
    values = sheet.getRange(1,i,num_rows,1).getValues()
    for(var j = 0; j < values.length; j++){
      if (values[j].includes(string )){
        var ret_val = true
    }
  }
  }
  return ret_val;
}

function dropRowsFromLeadSheet(){
  var ls_id = 'SHEET1_ID';
  var ss = SpreadsheetApp.openById(ls_id);
  SpreadsheetApp.setActiveSpreadsheet(ss);
  var sheet = ss.getSheets()[0];
  var num_rows = sheet.getLastRow().toString(); //gets row count of 
  var num_rows = num_rows.replace(".0","");
  for (var i = 5; i < 7; i++){
    values = sheet.getRange(1,i,num_rows,1).getValues() //gives me a 2D array of all the values in the column
    for(var j = values.length; j>=0; j--){ //had to go from bottom up because of how Google sheets works
      var array = values[j] //getting each individual array within the 2D array
      if(typeof array !== null){
        if(array.length == 1) { // <---- Here is where the error says the code is breaking
          var string = array[0]
          if(CheckDNCList(string)){
            sheet.deleteRow(j)
          }
        }
      }
    }
  }
}

我假设由于 length 命令不起作用,二维数组中的一个值是 null 或其他东西,但我写了一个循环将所有唯一类型添加到数组中,数组中唯一的值是

 object
。由于我只使用
getRange()
命令拉出一列,因此长度应始终为 1 或 0。为什么会出现此错误?

javascript arrays google-apps-script
© www.soinside.com 2019 - 2024. All rights reserved.