Google Drive文件夹创建函数异常:因Array原型扩展生成多余文件夹
Hey there, let's tackle this root cause once and for all. The issue you're facing happens because your custom Array.prototype.findIndex is polluting the global Array prototype—when the code iterates over folder items, it's accidentally picking up this prototype method as if it were a folder name, hence that weird code-named folder popping up.
Instead of patching it with post-creation cleanup, let's rewrite the getDriveFolder function to avoid relying on the potentially tainted findIndex method entirely. Here's the revised version:
function getDriveFolder(folderName, parentFolder) { // Use DriveApp's native folder iterator to avoid prototype-polluted Array methods const folders = parentFolder.getFolders(); let targetFolder = null; // Manually iterate through folders to find the match while (folders.hasNext()) { const currentFolder = folders.next(); if (currentFolder.getName() === folderName) { targetFolder = currentFolder; break; } } // Create the folder if it doesn't exist if (!targetFolder) { targetFolder = parentFolder.createFolder(folderName); } return targetFolder; }
Key changes that fix the problem:
- Ditched prototype-dependent methods: We're using
DriveApp's built-in folder iterator with awhileloop instead of relying onArray.prototype.findIndex. This completely avoids touching the polluted Array prototype. - Explicit, safe name matching: We only check the actual
getName()value of each folder, so there's no chance of accidentally matching the custom prototype method. - Preserves core functionality: The original logic (find existing folder or create a new one) stays fully intact—we're just making it immune to prototype pollution.
This approach is far more reliable than your temporary cleanup fix because it stops the rogue folder from being created in the first place, instead of having to clean up after the fact.
内容的提问来源于stack exchange,提问作者Jason Phillips

