【发布时间】:2018-06-01 05:42:26
【问题描述】:
我成功使用 ctrlq.org 中的以下代码在 Google Drive 中创建文件夹:
function go() {
var path = "//main//parent//child//grandchild”;
var folder = getDriveFolder(path);
Logger.log(folder.getUrl());
}
function getDriveFolder(path) {
var name, folder, search, fullpath;
// Remove extra slashes and trim the path
fullpath = path.replace(/^\/*|\/*$/g, '').replace(/^\s*|\s*$/g, '').split("/");
// Always start with the main Drive folder
folder = DriveApp.getRootFolder();
for (var subfolder in fullpath) {
name = fullpath[subfolder];
search = folder.getFoldersByName(name);
// If folder does not exit, create it in the current level
folder = search.hasNext() ? search.next() : folder.createFolder(name);
}
return folder;
}
我的一张工作表出现错误。在创建最后一个文件夹(孙子)之后,还会创建一个额外的文件夹。
文件夹的名称是: 功能(搜索){如果(搜索==“”){返回假; } for (var i = 0; i
是的,这实际上是在使用此电子表格的函数创建的每个路径的末尾创建的文件夹的名称。这让我发疯了。
通过反复试验,我发现在我的项目中包含以下代码会导致创建这个额外的文件夹。
这是导致问题的代码:
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i] == search) return i;
return -1;
}
是否可以重写 getDriveFolder 以防止这种情况发生?也许甚至只是通过过滤掉名字?我试过无济于事。非常感谢您的帮助。
我最终自己解决了这个问题。这可能不是最好的解决方案,但它确实有效。我添加了以下代码来过滤掉错误的文件夹名称。
if(folderName.indexOf("function (search") > -1) {
var folderParent = DriveApp.getFolderById(folderID).getParents().next();
DriveApp.getFolderById(folderID).setTrashed(true);
folder = folderParent;
【问题讨论】:
-
你刚刚被
for ... in迭代咬了! stackoverflow.com/questions/500504/…