我有一个生成随机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
答案 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()
支票拉入单独的功能,并根据结果返回true
或false
,以接受代码或生成新代码。
道格的观点是正确的,特别是如果你有一个非常大的电子表格。下面修改后的代码可以使用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
}
}
}