【问题标题】:How to refer to element in array in Google apps scripts如何在 Google Apps 脚本中引用数组中的元素
【发布时间】:2019-09-26 13:57:24
【问题描述】:

这是非常基本的,但我很难找到相关文档。

例如,我需要根据文件名获取文件 id。请注意,这是一个简化的示例,我的数组中可能有多个元素。

function getFileID() {
  var fileNames = ["my_file"];
  var Ids = [];
  Ids.push(fileNames.getId());
  Logger.log(Ids)
}

这将返回TypeError: Cannot find function getID in object ["my_file"]

因此,它将fileNames 视为一个完整的对象,而不仅仅是它包含的字符串值。

我尝试了以下,但这些也不对。

function getFileID() {
  var fileNames = ["my_file"];
  var Ids = [];
  Ids.push(fileNames[1].getId());
  Logger.log(Ids)
}
function getFileID() {
  var fileNames = ["my_file"];
  var Ids = [];
  var fileNames = (JSON.stringify(fileNames));
  Ids.push(fileNames.getId());
  Logger.log(Ids)
}

【问题讨论】:

    标签: javascript arrays google-apps-script


    【解决方案1】:

    它不在文档中的原因是它是一个 JavaScript 错误。字符串和数组没有 getId() 函数。 Google 文档有一个 getId() 函数,但字符串不是 google 文档,只是一段包含 google 文档名称的文本。

    您需要使用驱动应用程序根据文件的名称来获取文件的ID:

    function getFileID() {
      var fileNames = ["my_file"];
      var filename = fileNames[0]; //arrays start at 0
      //this will get the id of the first file with that name
      var file = DriveApp.getFilesByName(filename).next()
      var id = file.getId();
      var Ids = [];
      Ids.push(id);
      Logger.log(Ids)
    }
    
    

    【讨论】:

      【解决方案2】:

      尝试改变这个:

      function getFileID() {
        var fileNames = ["my_file"];
        var Ids = [];
        Ids.push(fileNames.getId());
        Logger.log(Ids)
      }
      

      这样的:

      function getFileID() {
        var folder=DriveApp.getFolderById("Folder Id");//might want to limit search to a folder
        var fnA=["Linked 1","Linked 2","Linked 3","Linked 4","Linked 5"];//filenames I picked some names that I had in a folder
        var ids=[];//array to collect names and ids
        for(var i=0;i<fnA.length;i++) {
          var files=folder.getFilesByName(fnA[i]);//often more than one file may have the same name
          while(files.hasNext()) {
            var file=files.next();
            ids.push({name:fnA[i],id:file.getId()});//storing name and file id in each array element.
          }
        }
        var html="";//building a dialog to view results
        for(var i=0;i<ids.length;i++) {
          html+=Utilities.formatString('<br />Filename: %s id: %s',ids[i].name,ids[i].id);
        }
        var userInterface=HtmlService.createHtmlOutput(html).setWidth(800);
        SpreadsheetApp.getUi().showModelessDialog(userInterface, "File names and ids");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        相关资源
        最近更新 更多