Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 优化google应用程序脚本中的循环_Javascript_For Loop_Indexing_Google Apps Script_Vlookup - Fatal编程技术网

Javascript 优化google应用程序脚本中的循环

Javascript 优化google应用程序脚本中的循环,javascript,for-loop,indexing,google-apps-script,vlookup,Javascript,For Loop,Indexing,Google Apps Script,Vlookup,我使用for循环搜索大型图纸(大约4500行)。 其中大多数看起来像这样: function lookup(value) { var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name"); var columnvalues = tables.getRange(1, 1,tables.getLastRow()).getValues(); var searchResult = columnvalues.f

我使用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;
}
函数查找(值){
var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“名称”);
var columnvalues=tables.getRange(1,1,tables.getLastRow()).getValues();
var searchResult=columnvalues.findIndex(value);//行索引-1
}
Array.prototype.findIndex=函数(搜索){
如果(search==“”)返回false;
对于(var i=0;i-1)返回i;
返回-1;
}

应用程序脚本当前运行相对较慢。我正在寻找一种方法,要么加快我当前的代码,要么寻找另一种搜索方法。我一直在考虑使用google电子表格查找功能(index match,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;
   };
}
函数查找(值){
var searchResult=false;
如果(值==“”)返回;
var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“名称”);
var columnvalues=tables.getRange(1,1,tables.getLastRow()).getValues();

对于(var i=0;i我发现搜索数组的最快方法是使用数组的.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()