javascript - 验证值是否在 Google 表格中
问题描述
我正在尝试生成一个随机代码,但在将其附加到 Google 表格之前,它需要检查代码是否已经在表格中,如果有,则需要再次重新随机,直到没有匹配。如何循环它直到Google表格中没有匹配项?您的回复将不胜感激。
这是我的 .gs 代码:
function processForm2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Sheet1");
var data = ws.getRange(5, 1, ws.getLastRow()-1, 1).getValues();
var code = Math.random().toString(36).substring(7);
var codeList = data.map(function(r){return r[0].toString(); });
var position = codeList.indexOf(code);
if(position < -1){
ws.appendRow([code]);
}else{
var code = Math.random().toString(36).substring(7);
ws.appendRow([code]);
}
}
解决方案
在你的情况下,如果position
不是循环-1
呢?当你的脚本被修改后,它变成如下。
从:
var code = Math.random().toString(36).substring(7);
var codeList = data.map(function(r){return r[0].toString(); });
var position = codeList.indexOf(code);
if(position < -1){
ws.appendRow([code]);
}else{
var code = Math.random().toString(36).substring(7);
ws.appendRow([code]);
}
至:
var codeList = data.map(function(r){return r[0].toString(); });
var code;
do {
code = Math.random().toString(36).substring(7);
var position = codeList.indexOf(code);
} while (position > -1);
ws.appendRow([code]);
参考:
推荐阅读
- spring - 为什么 Spring @ConstructorBinding 不绑定 Kotlin @ConfigurationProperties 类?
- javascript - 尝试在 discord.js 中创建货币系统(余额不是商店)
- javascript - JavaScript 似乎无法在控制台中运行
- python - Django 序列化程序错误预期数字,但得到 [28]
- android - Firebase“请求没有身份验证令牌”错误
- listview - ListView 作为 Flutter 中的 TabBar
- javascript - Vuex抽象通用继承方法(大SPA)
- sql - SELECT/HAVING 的 SQL 查询异常的执行顺序
- php - 添加一个表单域添加一个数学问题来阻止机器人?:(
- python - 在 Python 中,是否有一个内置函数来获取两个给定值之间的值(在列表中)?