优化循环在谷歌应用程序脚本

Optimizing for loops in google apps script

本文关键字:应用程序 脚本 谷歌 循环 优化      更新时间:2023-09-26

我使用for循环搜索大型表(大约4500行)。它们大多数看起来像这样:

function lookup(value) {
  var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name");
  var columnvalues = tables.getRange(1, 1,tables.getLastRow()).getValues(); 
  var searchResult = columnvalues.findIndex(value); //Row Index - 1
}
 Array.prototype.findIndex = function(search){
  if(search == "") return false;
  for (var i=0; i<this.length; i++)
    if (this[i].toString().indexOf(search) > -1 ) return i;
  return -1;
}

应用程序脚本目前运行相对较慢。我正在寻找一种方法,要么加快我当前的代码或另一种搜索方法。我一直在考虑使用谷歌电子表格查找功能(索引匹配,vLookup),但我还没有找到一种方法来访问这些功能在应用程序脚本。任何想法吗?

目前你找不到一种方法来做这个更快的应用程序脚本。您必须获得整个列并像您已经做的那样逐个搜索。

您提到的使用工作表公式的替代方法可能是不可靠的,因为您可能会发现单元格公式在更改值时不会立即更新结果。

我能看到的唯一情况是,如果你需要进行多个搜索调用,这个速度会加快。在这种情况下,将搜索项作为数组传递并在单循环中一次性搜索它们会更快。

当您搜索单个列时,一些更简单的东西可能会更快一些。

function lookup(value) {
  var searchResult = false;
  if(value == "") return;
  var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name");
  var columnvalues = tables.getRange(1, 1,tables.getLastRow()).getValues(); 
  for (var i=0; i<columnvalues.length; i++) {
    if(columnvalues[i][0] == value) {
      searchResult = i;  //Row Index - 1
      break;
   };
}

我发现通过数组搜索的最快方法是使用数组的.filter()方法。

var yourData = range.getValues();
var results = yourData.filter(function(val) { 
    return val[0] == search ||
     val[0].includes(search);
});
//now you have a 2d array of results

修改,使它是你想要的范围(对不起,在移动设备上),这是我发现的最快的方法。避免for循环是最好的。您还可以使用。foreach ()