使用Google App Script,当我使用Logger.log()时,for循环正确迭代,我得到每个值的结果。当我尝试将其输出到谷歌表时,只有每个变量的最后一个值一次又一次地输出目标数量。长度。
非常感谢任何帮助!
function listGoals() {
var sheet = SpreadsheetApp.getActiveSheet();
var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
var goals = filterList.items;
for (var i = 0, goal; goal = goals[i]; i++) {
var accountId = goal.accountId;
var propertyId = goal.webPropertyId;
var goalNumber = goal.id;
var goalName = goal.name;
Logger.log('accountId: ' + accountId);
Logger.log('profileId: ' + propertyId);
Logger.log('goal number: ' + goalNumber);
Logger.log('goal name: ' + goalName);
//Logger.log prints for each result
sheet.getRange(1,1,goals.length).setValue(goalNumber);
sheet.getRange(1,2,goals.length).setValue(goalName);
//this only prints out the last value of goalNumber and goalName to the sheet
}
}
答案 0 :(得分:1)
它不仅仅打印最后的结果,它只是用新的结果覆盖旧的结果。
goals.length
只有在您提供包含如此值的值的数组数组时才有帮助:
[[1, "Goal 1"],
[2, "Goal 2"]]
如果要打印出goalNumber
和goalName
的列表,则需要每次都要写入要写入的单元格。
sheet.getRange(1+i,1).setValue(goalNumber);
sheet.getRange(1+i,2).setValue(goalName);
为了加快这个过程,不要对每个目标进行两次调用,你可以将id名称对作为数组存储在一个数组中,并在循环完成后执行一次最终的setValues
调用。
function listGoals() {
var sheet = SpreadsheetApp.getActiveSheet();
var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
var goals = filterList.items;
var goalsToWrite = [];
for (var i = 0, goal; goal = goals[i]; i++) {
goalsToWrite.push([goal.id, goal.name]);
}
sheet.getRange(1, 1, goals.length, 2).setValues(goalsToWrite);
}