我有一个循环遍历数组C:D的函数在A:B中找到一个匹配,如果有,它用B替换B中的值,如果没有匹配则将C:D附加到A:B。此函数正在使用循环。我知道有一种优化方法,但我迷路了。如何在没有循环的情况下运行此脚本?
function moveValues() {
var ss = SpreadsheetApp.openById('open_id');
var source = ss.getRange('sheet2!D:C');
var destination = ss.getRange('sheet2!A:B');
var destCount = 0;
for (var j = 1; j <= destination.getLastRow(); j++) {
if (destination.getCell(j,1).getValue() == "") {
destCount = j;
break;
}
}
for (var i = 1; i <= source.getLastRow(); i++) {
Logger.log(source.getLastRow());
var added = false;
var targetName = source.getCell(i,1).getValue();
var copyValue = source.getCell(i,2).getValue();
if (targetName == "") {
break;
}
for (var j = 1; j <= destCount; j++) {
var curName = destination.getCell(j,1).getValue();
if (copyValue != "" && targetName == curName) {
destination.getCell(j, 2).setValue(copyValue);
added = true;
break;
}
}
if (!added) {
destination.getCell(destCount, 1).setValue(targetName);
destination.getCell(destCount, 2).setValue(copyValue);
destCount += 1;
}
}
source.clear();
};
答案 0 :(得分:1)
您仍然需要使用循环,但可以优化代码。一开始就使用getValues()
。返回一个2D数组。您可以使用.indexOf()
来确定另一个数组中是否存在匹配。
function moveValues() {
var i,L,sh,ss,srcRng,destRng,srcData,targetData,v;
ss = SpreadsheetApp.openById('open_id');
sh = ss.getSheetByName('sheet2');//Get sheet2
lastRow = sh.getLastRow();//Get the row number of the last row
srcRng = sh.getRange(1,1,lastRow);//Get the range for all the values in column 1
destRng = sh.getRange(3,1,lastRow);//Get the range for all the values in column 3
srcData = srcRng.getValues();//Get a 2D array of values
targetData = destRng.getValues();//Get a 2D array of values
srcData = srcData.toString().split(",");//Convert 2D to 1D array
targetData = targetData.toString().split(",");//Convert 2D to 1D array
L = srcData.length;
for (i=0;i<L;i++) {//Loop the length of the source data
v = srcData[i];//Get this value in the array
if (targetData.indexOf(v) !== -1) {//This value was found in target array
}
}
这不是你问题的完整答案,但希望它会给你一些想法。
在此示例中,代码只获取要比较的数据列,而不是要更改的数据列。