我尝试使用一个"for in“或"for each”循环遍历多个数组。
我有三个数组,即name、id 和 available。这些数组的大小相等。
我需要做的是迭代上述数组的每个值,并基于行和列的索引(分别为i和j的值),将元素的值复制到电子表格中的一个单元格中。
下面是我使用的代码:
for (i = 1; i <= copy_range.getNumRows(); i++) {
for (j = 1; j <= copy_range.getNumColumns(); j++) {
if (j == 1) {
var name_cell = copy_range.getCell(i, j);
// I want to do this however I'm not able to do this since I already have i and j for
// row and column iteration and that another nested loop makes things complicated
name_cell.setValue(name[k]);
}
else if (j == 2) {
var id_cell = copy_range.getCell(i, j);
Logger.log(id_cell.getA1Notation());
id_cell.setValue(id[k]); //Same idea as in previous if
}
else {
var availability_cell = copy_range.getCell(i, j);
Logger.log(availability_cell.getA1Notation());
availability_cell.setValue(available[k]); //Same as if and else if loops previously.
}
}
我不能使用索引的原因是,我已经使用i
和j
作为迭代变量来引用行和列,并且使用另一个嵌套循环不会给我提供预期的输出-它会导致不必要的迭代和执行时间。
请让我知道是否有任何方法可以使用"for in“或类似的循环来迭代所有三个数组中的每一项。
发布于 2018-10-07 04:55:58
在我看来,您似乎有三个包含N个条目的“列”数组,并且希望将它们写入N行3列的范围(名为copy_range
)。要做到这一点,最好的方法是将这3个数组连接到可在单个调用中直接写入的必需2D数组:
const output = name.map(function (nameVal, row) {
return [nameVal, id[row], availability[row]];
});
copy_range.setValues(output);
上面的代码使用Array#map
方法迭代name
数组,并将与每个元素nameVal
关联的索引指定为row
。然后使用row
访问id
和availability
数组中的相应元素。
https://stackoverflow.com/questions/52680512
复制相似问题