我正在努力弄清楚为什么我在这里使用的Javascript include()函数不匹配并返回true。该代码用于Google工作表上的Google脚本中,以填充某些单元格值。下面是完整脚本中的相关代码:
const currentYear = getCurrentYear();
//Get current year from active sheet name
function getCurrentYear(){
year = sheetName.slice(-7, -2);
return year; //returns "2020"
}
//Return Current Control File ID
function getCurrentControlFileId(){
const controlFolder = DriveApp.getFolderById(controlFolderId);
const controlFiles = controlFolder.getFiles();
while (controlFiles.hasNext()){
let controlFile = controlFiles.next();
let currentControlFileName = controlFile.getName(); // Evaluates to "CONTROL 2020"
let searchString = `${currentYear}`; // Evaluates to "2020"
//Have also tried:
//let searchString = currentYear;
if (currentControlFileName.includes(searchString)){
let controlFileId = controlFile.getId();
return controlFileId;
}
}
}即使controlFile.getName()值为“Control2020”且searchString值为"2020“,controlFile.getName().includes(searchString)也会返回false。两者都是字符串。如果我手动在if语句条件中输入"2020“,如下所示:
controlFile.getName().includes("2020")它返回true并按预期工作,返回ID字符串。我还尝试过将currentYear和controlFile.getName()包装在String()中,但仍然返回false。我真的看不出这里有什么问题,希望能得到一些帮助。
发布于 2020-09-24 23:09:36
最有可能的情况是,year包含一个空格
你可以用Logger.log(year.length);再检查一遍。
注意,在使用array.slice(start, end)时,末尾索引是结果中未包含的第一个元素。因此,如果您期望输出为"2020“(对应于year.length=4):
end-start应等于4。
如果您的工作表名称类似于"XXX 2020 YY",则应将year的定义修改为
year = sheetName.slice(-7, -3);
https://stackoverflow.com/questions/64048198
复制相似问题