0

我有一個循環通過數組C:D在A:B中找到匹配的函數,如果有它用D替換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(); 
}; 
+2

每個getCell api調用都需要時間,所以使用.getValues()只需要一次,它會返回一個包含範圍值的二維數組,這會更快。還要在一個範圍內使用.setValues(newValues)設置新值,最後只能調用一個api。 –

回答

1

您仍然需要使用循環,但代碼可以進行優化。在開始時使用getValues()。這返回一個二維數組。您可以使用.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 

    } 
    } 

這不是一個完整的回答你的問題,但希望它會給你一些想法。

在這個例子中,代碼只是獲取要比較的數據列,而不是要更改的數據列。