数组中的变量返回为Undefined

时间:2017-11-02 15:25:39

标签: arraylist google-apps-script

var activeSP = SpreadsheetApp.getActiveSpreadsheet();

  var sheets ;
  var currentSheet; 
  var sheetName ;

  for(i = 0; (activeSP.getNumSheets()-1) != 0;i++) {

    sheets = activeSP.getSheets();
    currentSheet = sheets[i] ; //Where i think the error is
    sheetName = currentSheet.getSheetName() ;

    if(sheetName != dailyName) {
      activeSP.deleteSheet(currentSheet) ;
      }
    else {
    i++
    }
  }
}

我有这个脚本。我们的想法是删除所有工作表,但删除具有所需名称(dailyName)的工作表。但是,当我尝试使 currentSheet 时,ArrayList的当前值返回为undefined。如果有人可以帮助我,我会非常感激。这是为了学校的工作。

  

错误:TypeError:无法调用方法" getSheetName"未定义的。

1 个答案:

答案 0 :(得分:0)

部分问题在于您在循环的每个步骤中调用getSheets()。此外,当您从数组中删除项目时,向后工作效率更高,因此您的循环在每次传递时都不会返回到索引0。

这是一个有效的功能:

function sheetToDelete() {
  var activeSP = SpreadsheetApp.getActiveSpreadsheet();
  var dailyName = "img"; // Set this somewhere

  var sheets ;
  var currentSheet; 
  var sheetName ;

  // Get the sheets as an array
  sheets = activeSP.getSheets();

  // run the loop backwards
  for(var i = (sheets.length - 1); i >= 0; --i) {

    // get the name of the current index
    currentSheet = sheets[i].getName();

    // Test for a match. If it doesn't delete the sheet
    if(dailyName !== currentSheet) {
      // currentSheet is a string right now, so use the index position
      activeSP.deleteSheet(sheets[i]) 
    }     
  }
}

在循环中也不需要else语句,因为如果条件不匹配,它将移动到数组的下一个项目。

相关问题