繁体   English   中英

在While循环内嵌套For循环

[英]Nested For Loop Inside While Loop

我正在创建一个脚本,将多个Google表格从一个google驱动器位置复制到另一个位置,然后在这些表格上循环并应用权限/编辑器。 我还必须跟踪先前已复制了源位置中的哪些工作表。

我的问题是while循环内的for循环。 由于某些原因,在while循环的单次迭代之后,运行my for循环的变量似乎采用了文件名的值。

while (files.hasNext()) {

    var file = files.next();

    for (var k in check){
      Logger.log(check[k]);
      if(check[k] = file.getName()){

        Logger.log("this file has been copied already");
        break;
      }
      else{
        Logger.log("this file was not found on the list, copying");
        file.makeCopy(file.getName(),copyFolder);
        ss = SpreadsheetApp.open(copyFolder.getFilesByName(file.getName()));
        ss.addEditors(admins);
        ss.addEditors(editors);

        var sheets = ss.getSheets();

        for (var y in sheets) {
             Logger.log(sheets[k].getSheetName());
             var protection = sheets[y].protect();
             protection.addEditors(admins);
             protection.removeEditors(editors);
           }


        checkSheet.appendRow(file.getName());
        Logger.log("file copied, file name appended to check list");

      }



    }

  }

这是输出日志。 正如您在for循环的第一次迭代中看到的那样,将记录数组中的正确值,即。 “列出的文件”。 从第二次迭代开始,check [k]的值将以某种方式分配给文件名,即。 “批处理权限”,“ CP-007791”。

[19-07-08 11:06:49:423 MDT] LISTED FILE
[19-07-08 11:06:49:424 MDT] this file has been copied already
[19-07-08 11:06:49:425 MDT] batch permissions
[19-07-08 11:06:49:425 MDT] this file has been copied already
[19-07-08 11:06:49:426 MDT] CP-007791
[19-07-08 11:06:49:427 MDT] this file has been copied already
[19-07-08 11:06:49:428 MDT] batch permissions 2
[19-07-08 11:06:49:429 MDT] this file has been copied already
[19-07-08 11:06:49:430 MDT] CP-008504
[19-07-08 11:06:49:431 MDT] this file has been copied already
[19-07-08 11:06:49:432 MDT] CP-007796
[19-07-08 11:06:49:433 MDT] this file has been copied already
[19-07-08 11:06:49:434 MDT] CP-007802
[19-07-08 11:06:49:435 MDT] this file has been copied already
[19-07-08 11:06:49:436 MDT] CP-003675
[19-07-08 11:06:49:437 MDT] this file has been copied already
[19-07-08 11:06:49:438 MDT] CP-007317
[19-07-08 11:06:49:439 MDT] this file has been copied already
[19-07-08 11:06:49:440 MDT] WO 81382901

我觉得我只是在这里错过了一些真正简单的事情。 让我知道您能否提供帮助。 谢谢

问题与解决方案

没错,只是在if语句条件check[k] = file.getName()使用了赋值=而不是比较运算符=== 您可以通过将其更改为check[k]===file.getName()来修正您的问题。

改善点

同样,为了使答案更有意义,您可以通过将file.getName()写入变量(例如var name = file.getName() file.getName()来优化代码,以仅在if...else语句之前和for循环之外访问文件名一次var name = file.getName() 这将为您节省对getName()三个调用。

有用的链接

  1. 作业员参考 ;
  2. 比较运算符参考 ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM