首页 > 解决方案 > 验证值是否在 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]);      
  }
}

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


在你的情况下,如果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]);

参考:


推荐阅读