arrays - 使用脚本从 googlesheets 中的数组返回下一个元素
问题描述
我在谷歌表中有一个名字列表。我正在尝试在谷歌应用程序脚本中创建一个函数,将列表中的下一个名称输出到电子表格中的不同单元格。一旦我返回了每个名字,我想回到开始。
我也尝试过使用 for 循环,但是脚本只是循环遍历每个项目,最后我只返回了最后一个项目。
function returnNextName() {
var nameList =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My
Homeroom").getRange(2, 1, 22).getValues();
var outputCell =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My
Homeroom").getRange(1, 4);
var i = 0;
i = i + 1;
i = i%nameList.length;
var nextName = outputCell.setValue(nameList[i]);
}
我的目标是每次运行该函数时,我都会获得列表中的下一个名称。但是,我只得到名字。
解决方案
每次调用脚本时都会重新定义
var i = 0;
i = i + 1;
i = i%nameList.length;
所以你的元素nameList[i]
总是一样的。
为避免这种情况,您需要按照 TheMaster 的建议使用PropertiesService 。
ScriptProperties
允许您将最后一个索引存储在脚本属性中,并在每次使用脚本时检索和修改它。
样本:
if(PropertiesService.getScriptProperties().getKeys().length==0){ // first time you run the script
PropertiesService.getScriptProperties().setProperty('i', 0);
}
var i = Number(PropertiesService.getScriptProperties().getProperty('i'))%nameList.length;
outputCell.setValue(nameList[i][0]);
i++;
PropertiesService.getScriptProperties().setProperty('i', i);
推荐阅读
- c# - C# UI 测试 WinAppDriver Appium 测试颜色?
- python - 模型表与用户的连接(标准登录模块)。姜戈,蟒蛇
- powershell - 如果未设置 TFS 构建变量,如何回退到默认值?
- multithreading - C++ boost::thread 在程序运行时变慢
- html - 试图让我的横幅图像跨越页面的宽度
- python - 在 matplotlib 中仅向图例的一个组件添加背景颜色
- javascript - 动态 javascript 滚动无法按预期工作
- r - ``data.table`` 对象,嵌套在 ``xgboost`` 对象中,保存为 ``.rda`` 时不会加载
- vue.js - this.$store 在示例应用程序结构之后未定义
- php - 如何解决这个 laravel 迁移错误创建数据库表?