如何生成随机3个字母的字符串并检查范围内的重复项

时间:2017-05-04 14:50:44

标签: google-apps-script google-sheets

我有一个生成随机3个字符串的脚本。它被用在一个更大的脚本中,其中字符串被附加到工作表中的下一行。

如果找到匹配项,我该怎么做才能搜索先前字符串的重复项范围并重复该功能?

 function stringGen(len)
 {
   var text = " ";
   var charset = "abcdefghijklmnopqrstuvwxyz";

   for( var i=0; i < len; i++ )
      text += charset.charAt(Math.floor(Math.random() * charset.length));

   return text; 
 }

   logger.log(3);

示例表:https://docs.google.com/spreadsheets/d/1Y_4R9XT5D31wwrbJOq8ClipdmIByLV0-nlTc2wZl-qM/edit#gid=0

1 个答案:

答案 0 :(得分:2)

原始

如果它们都在相同的范围内(即列或行),您可以将范围作为数组获取,然后使用indexOf()检查匹配项。像这样:

function stringGen(len) {
   // assume the array starts in A1 and runs down colA
   var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

   // getValues() returns an array
   var range = sheet.getRange(1,1,sheet.getLastRow(),1).getValues();

   var text = " ";
   var charset = "abcdefghijklmnopqrstuvwxyz";

   for( var i=0; i < len; i++ )
      text += charset.charAt(Math.floor(Math.random() * charset.length));
   }

   // an index of -1 means the value is not in the array.
   if(range.indexOf(text) > -1) {
     return text;
   }

   logger.log(3);
}

您还可以将indexOf()支票拉入单独的功能,并根据结果返回truefalse,以接受代码或生成新代码。

更新

道格的观点是正确的,特别是如果你有一个非常大的电子表格。下面修改后的代码可以使用for循环:

function stringGen() {
   // assume the array starts in A1 and runs down colA
   var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

   // getValues() returns an array
  var range = sheet.getRange(1,1,sheet.getLastRow(),1).getValues();

  var text = " ";
  var charset = "abcdefghijklmnopqrstuvwxyz";

  for( var i=0; i < 3; i++ ) {
    text += charset.charAt(Math.floor(Math.random() * charset.length));
  }

  // Loop through every element in the range
  for(var j in range) {
    if(range[j].toString() == text) {
      Logger.log('matched');
    } else {

      // Write one code to the next line and stop the loop
      sheet.getRange((sheet.getLastRow()+1), 1).setValue(text);
      break
    }
  }
}