【问题标题】:Google App Script IF ELSE logic not correct如果 ELSE 逻辑不正确,Google App 脚本
【发布时间】:2015-07-30 14:47:29
【问题描述】:

我有一个将文件从一个文件夹复制到另一个文件夹的 Google App 脚本。首先,它检查源文件夹中是否有任何文件。如果有,它会删除目标文件夹中的文件,然后将文件从源文件夹复制到目标。复制完成后,它应该从源文件夹中删除文件。但是,它并没有像我期望的那样工作,我相信问题出在ifelse 声明中。我在 if else 语句中有一个 while 循环。我的想法是while 循环会在它检查if 语句之前完成,但情况似乎并非如此。

问题是脚本删除了目标文件夹中的一个文件,而不是保留这两个文件。 (我现在只有 2 个文件)。

这是我的代码:

while(sourceFolders.hasNext()){
    var sourceFolder = sourceFolders.next();
    var sourceFiles = sourceFolder.getFiles();

    // Check to see if there are new files to copy
    if(sourceFiles.hasNext()){
      //++ If so, delete the files in the target folder  
      deleteTheFiles(TARGET_FOLDER);

      //++ Copy new files to target folder
      while(sourceFiles.hasNext()){
        var sourceFile = sourceFiles.next();
        var sourceFileName = sourceFile.getName();
        sourceFile.makeCopy(sourceFileName, TARGET_FOLDER);
        //++ Delete files in source folder
        sourceFile.setTrashed(true);
      }
    //-- If not, do nothing
    } else {
      Logger.log('There are not files at this time.')
    }
}

【问题讨论】:

  • 显示deleteTheFiles() 函数。使用debugger 逐行遍历代码。
  • 请编辑以提供能够重现问题的最少代码。 minimal reproducible example
  • 我编辑了它。我希望这可以帮助你帮助我!
  • sourceFiles.hasNext() 仅在文件超过 1 个时为真。此外,每次您的脚本找到一个包含文件的新文件夹时,它都会删除它刚刚从最后一个源文件夹复制到 TargetFolder 的所有文件...
  • @Cole9350 正确。那部分似乎工作正常。似乎正在发生的事情是if 声明不止一次是true,这让我知道为什么会发生这种情况。我会发布一个答案。

标签: javascript google-apps-script


【解决方案1】:

因为我在源中有多个文件夹,所以第一个 while 循环不止一次迭代,因此触发了 deleteTheFiles() 函数,该函数正在删除放入目标文件夹的第一个文件。我在while 循环之外创建了一个简单的counter 变量,从而解决了这个问题。代码如下:

function copyFilesToBackup() {  
  var sourceFolders = SOURCE_FOLDER.getFolders();
  var counter = 0; // <-- ADDED THIS COUNTER -->
  while(sourceFolders.hasNext()){ // <-- HERE IS THE PROBLEM
    var sourceFolder = sourceFolders.next();
    var sourceFiles = sourceFolder.getFiles();

    // Check to see if there are new files to copy
    if(sourceFiles.hasNext()){
      //++ If so, delete the files in the target folder  
      if(counter < 1){ <-- SINCE WE ONLY NEED TO DELETE THE TARGET ONCE -->
        deleteTheFiles(TARGET_FOLDER);
        counter++; <-- INCREMENT COUNTER -->
      }
      //++ Copy new files to target folder
      while(sourceFiles.hasNext()){
        var sourceFile = sourceFiles.next();
        var sourceFileName = sourceFile.getName();
        sourceFile.makeCopy(sourceFileName, TARGET_FOLDER);
        //++ Delete files in source folder
        sourceFile.setTrashed(true);
      }
    //-- If not, do nothing
    } else {
      Logger.log('There are not files at this time.')
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多