javascript - 如何让for循环脚本更加高效?

标签 javascript optimization google-apps-script google-sheets

总的来说,我对脚本编写非常陌生,尤其是在 GAS 方面,并且希望确保我养成良好的习惯。我编写了一个 for 循环脚本,本质上执行以下操作:

  1. 从第 2 行开始通读 A 列
  2. 如果 for 循环中当前单元格上方的单元格的值相同,则清除当前单元格右侧相邻单元格的内容。

例如

单元格 A1 包含“某物”。单元格 B1 包含“令人兴奋”

单元格 A2 包含"new"。单元格 B2 包含“X”

单元格 A3 包含"new"。单元格 B3 包含“Y”

由于 A3 与单元格 A2 具有相同的值(该值为“New”),因此单元格 B3(当前值为“Y”)被清除,因此单元格 B3 中没有任何值。

运行起来似乎需要很长时间,我确信这是由于我的新手写作造成的,我想让这个脚本尽可能高效。

各位脚本大神有什么建议可以让这个脚本更加高效吗?

我也希望能解释一下为什么任何建议对于我自己的理解来说会更有效,这样任何碰巧发现这篇文章的人以后也能理解它。

这是脚本:

function testCode() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheetByName("Test 1");
 var source = sheet.getRange("A2:A");

 for (i = 2; i < source.getLastRow(); i++) {
 var currentCell = sheet.getRange(i,1).getValue();
 var cellAbove = sheet.getRange(i-1,1).getValue();
 var cellRight = sheet.getRange(i,2);
 if (currentCell == cellAbove){
 cellRight.clearContent(),({contentsOnly:true});
  }
 }
}

谢谢

最佳答案

最大的问题是您在每个循环中都会获得三个新范围。有一种方法可以做到这一点,而无需在循环中获取新的范围。您需要获取 A 列和 B 列中的数据。

function testCode() {
  var cellAbove,currentCell,cellRight,data,lastRow,L,sheet,source,ss;

  ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("Test 1");
  lastRow = sheet.getLastRow();

  source = sheet.getRange(2,1,lastRow-1,2);//Get data starting in row 2 and column 1
  //Get the number of rows that are the lastRow minus the number of rows not included 
  //at the top - get 2 columns

  data = source.getValues();//Get a 2D array of values
  L = data.length;//Get the number of elements in the outer array- which is the number of
  //rows in the array

  for (var i = 0; i < L; i++) {

    if (i == 0) {continue;} //If this is the first loop there is no value above it to check

    currentCell = data[i][0];
    cellAbove = data[i-1][0];

    if (currentCell == cellAbove){
      cellRight = sheet.getRange(i+1,2);
      cellRight.clearContent(),({contentsOnly:true});
    }
  }
}

关于javascript - 如何让for循环脚本更加高效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48068860/

相关文章:

javascript - 从 Outlook 365 错误发送电子邮件 nodemailer

matlab - 在Matlab中优化大量的fsolve调用

google-apps-script - 使用自动脚本发送电子邮件

google-apps-script - 如何通过api基于插入行触发Google Apps脚本功能

javascript - 如何获取数字形式的值并将其转换为字符串javascript

javascript - 全日历 : disableResizing is only working on month view

javascript - 通过 Lightbox(或类似的)从超链接查看图像

缓存未命中?我怎么能看到那个?

java - JRE 7 JVM 更新和优化

javascript - 将 Google 电子表格日期转换为 JS 日期对象?