我正在尝试列出树结构中的所有文件。我在网上找到了以下代码,但是将文件夹和文件名输出到错误日志中。 (我使用BetterLog将其发送到电子表格。我希望在函数运行时将信息保存到数组中,问题是函数是递归的,我无法弄清楚如何解决这个问题。
function getChildFolders(parent) {
Logger = BetterLog.useSpreadsheet('1nJ3fTFYQgwwXYik3LqAoX2M1KHj4lskrxyX0Y9p6ci8');
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
Logger.log("Folder Name: " + childFolder.getName());
Logger.log("Folder URL: " + childFolder.getUrl());
var files = childFolder.getFiles();
while (files.hasNext()) {
// Print list of files inside the folder
Logger.log(files.next().getName());
}
// Recursive call for any sub-folders
getChildFolders(childFolder);
}
}
答案 0 :(得分:1)
好吧,只需将数组作为函数的参数传递,如下所示:
function getChildFolders(parent,array) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
array.push("Folder Name: " + childFolder.getName());
array.push("Folder URL: " + childFolder.getUrl());
var files = childFolder.getFiles();
while (files.hasNext()) {
// Print list of files inside the folder
array.push(files.next().getName());
}
// Recursive call for any sub-folders
getChildFolders(childFolder, array);
}
return array;
}
function test() {
var array = getChildFolders(DriveApp.getRootFolder(), []);
Logger.log(array);
}