[英]For Loop with Changing Variable Names
I would like to create a for loop that performs the same operation with different variable names.我想创建一个 for 循环,用不同的变量名执行相同的操作。 For instance;例如; in the below code, I would like to loop the code 6 times, and every instance of the word "civil" would be variable based on values in an array.在下面的代码中,我想循环代码 6 次,并且单词“civil”的每个实例都将根据数组中的值而变化。
civilSheet.activate();
//grab values from column A and determine which rows the Hot List, Coordination Items, and Responsibilities information
var civilData = civilSheet.getRange('A:A').getValues();
for(var j=0;j<civilData.length;j++){
if(civilData[j] == "~Hot List~"){
var civilHot = j+3;
} else if(civilData[j] == "~Coordination Items~"){
var civilCoord = j+1;
} else if(civilData[j] == "~Responsibilities~"){
var civilResp = j+1;
}
}
The goal is something along the lines of the below code:目标类似于以下代码:
var variableNames = ["civil", "struct", "avl", "fpm", "electrical", "arch"];
for(var i=0;i<variableNames.length;i++){
var i+"Data" = i+"Sheet".getRange('A:A').getValues();
for(var j=0;j<i+"Data".length;j++){
if(i+"Data"[j] == "~Hot List~"){
var i+"Hot" = j+3;
} else if(i+"Data"[j] == "~Coordination Items~"){
var i+"Coord" = j+1;
} else if(i+"Data"[j] == "~Responsibilities~"){
var i+"Resp" = j+1;
}
}
}
You don't need dynamic variables names.您不需要动态变量名称。 You need variables to dynamically refer to different objects.您需要变量来动态引用不同的对象。 You can simply add a another for-loop with arrays to reuse the same code.您可以简单地使用 arrays 添加另一个 for 循环来重用相同的代码。
Assuming variableNames
are sheetNames
,假设variableNames
是sheetNames
,
const sheetNames = ['civil', 'struct', 'avl', 'fpm', 'electrical', 'arch'];
const ss = SpreadsheetApp.getActive();
for (let si = 0; si < sheetNames.length; si++) {
let thisSheet = ss.getSheetByName(sheetNames[si]);
let thisData = thisSheet.getRange('A:A').getValues();
for (let j = 0; j < thisData.length; j++) {
if (thisData[j][0] == '~Hot List~') {
let thisHot = j + 3;
} else if (thisData[j][0] == '~Coordination Items~') {
let thisCoord = j + 1;
} else if (thisData[j][0] == '~Responsibilities~') {
let thisResp = j + 1;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.