以下 Javascript 挂起。我一直在自学 Apps 脚本来对工作表上的数据进行排序。在过去的两个小时里,我和我的网络开发人员 friend 一直不明白为什么这个特定的脚本会停止。它只是说永远运行脚本......
发生的情况是,我将电子表格的一部分指定为日历区域,该区域已经由我的其他功能之一打印了动态日历。出于测试目的,我隔离了这个函数并给它一个虚拟数组,但该函数应该循环遍历日历,找到“日期”的坐标,即第 1、2、3、4 号,并返回该日期下方的空单元格的坐标(我将数据放入日历的地方)。
function printCalendarValues(array){
var array = [0,143,534,342,54,1,41,1];
var Calendar_Display_range = recruiter_sheet.getRange('B8:H19');
var Calendar_Display_values = Calendar_Display_range.getValues();
function getCellBelow(day, rangeArray){
for(i=0; i<rangeArray.length; i++){
for(j=0;j<rangeArray[i].length; j++){
if(rangeArray[i][j]==day){
var res = [i+9,j+2];
return res;
};
};
}
};
for(i=0;i<2;i++){ //< ---- THIS IS WHERE IT BREAKS
// If I take the code in this for loop out of it and run it
// only once then it runs as expected. It breaks when I put it in
// this for loop. You can see I only loop twice right now. I
// did that for testing, but i've tried twice, or array.length
// anything other than running it once breaks it.
var cellBelow = getCellBelow(i+1, Calendar_Display_values);
recruiter_sheet.getRange(cellBelow[0],cellBelow[1]).setValue(array[i]);
};
};
最佳答案
您需要定义变量 i
在你的函数的顶部。
function printCalendarValues(array){
var i;//Define i - its' value will be undefined
或者您需要添加var
for
内的关键字参数。 for (var i = 0, etc
现在,变量 i
是一个全局性的。 i
的值是在“全局范围内”。您运行的任何函数都可以访问 i
就像现在一样。
当你的第二个for
循环调用 getCellBelow
功能,两者都是for
循环和函数getCellBelow
正在共享变量 i
。所以,i
设置为 1,则函数 getCellBelow
被叫。然后i
被设置回零。所以你的for
循环将永远持续下去。它永远不会达到 1。它不断被 getCellBelow
设置回零。功能。
for(i=0;i<2;i++){ //i gets set to zero and then incremented to 1
var cellBelow = getCellBelow(i+1, Calendar_Display_values);//function called
然后在函数 getCellBelow 中;
for(i=0; i<rangeArray.length; i++){//i is set to zero and until the array lengh
所以,i
现在很容易大于一。还有你的循环for(i=0;i<2;i++){
将停止。
您可以通过添加 Logger.log('i: ' + i)
来看到这一点语句,然后查看日志。在“查看”菜单中,选择运行代码后的“日志”。
您应该定义i
函数内部 function getCellBelow(day, rangeArray){
应该是:
function getCellBelow(day, rangeArray){
var i;
那么,i
的用法该函数内部将仅限于该函数,并且不会影响 i
的任何其他值在该函数之外。
关于javascript - Google Apps 脚本挂起 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45112103/