gpt4 book ai didi

javascript - 如何在 Google 应用程序脚本中引用数组中的元素

转载 作者:行者123 更新时间:2023-11-30 11:00:12 24 4
gpt4 key购买 nike

这是非常基础的,但我正在努力寻找这方面的文档。

例如,我需要根据文件名获取一个文件id。请注意,这是一个简化的示例,数组中可能有多个元素。

function getFileID() {
var fileNames = ["my_file"];
var Ids = [];
Ids.push(fileNames.getId());
Logger.log(Ids)
}

这将返回 TypeError: Cannot find function getID in object ["my_file"]

因此,它将 fileNames 作为整个对象读取,而不仅仅是它包含的字符串值。

我尝试了以下,但这些也不对。

function getFileID() {
var fileNames = ["my_file"];
var Ids = [];
Ids.push(fileNames[1].getId());
Logger.log(Ids)
}
function getFileID() {
var fileNames = ["my_file"];
var Ids = [];
var fileNames = (JSON.stringify(fileNames));
Ids.push(fileNames.getId());
Logger.log(Ids)
}

最佳答案

它不在文档中的原因是它是一个 JavaScript 错误。字符串和数组没有 getId() 函数。谷歌文档有一个getId()函数,但是这个字符串不是谷歌文档,只是一段包含谷歌文档名称的文本。

您需要根据文档的名称使用驱动程序应用程序,然后您可以获得ID:

function getFileID() {
var fileNames = ["my_file"];
var filename = fileNames[0]; //arrays start at 0
//this will get the id of the first file with that name
var file = DriveApp.getFilesByName(filename).next()
var id = file.getId();
var Ids = [];
Ids.push(id);
Logger.log(Ids)
}

关于javascript - 如何在 Google 应用程序脚本中引用数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58118466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com