这是我要问的关于这个功能的第三个问题(我应该在这一点完全重做它,也许)。
该函数构建一个参数定义大小的网格,并从函数中插入数据,也可以定义参数。我试图能够在包含唯一对象的网格中创建网格,尽管已经有很多问题得到了很大的回答here和here *谢谢@Bergi,我还有另一个:
这是代码,有一些日志到控制台以显示内部的内容:
//Build a 3x3 grid constructor that can optionally pre-insert values into each cube
function buildGrid(rows,cols,dataFunction){
console.log("Let's see, we have an order for "+rows+" rows, "+cols+" cols and within each,"+dataFunction);
//check to see if dataFunction provided, and type
if(arguments.length !== 3){
dataFunction = function(){return 0;};
}
var customGrid = [];
//create grid
for(row=0;row<rows;row++){console.log("creating row "+(row+1)+" of "+rows);
var customRow = [];
for(col=0;col<cols;col++){console.log("creating col "+(col+1)+" of "+cols);
if(typeof dataFunction == 'function'){
data = dataFunction();
}
else{
data = dataFunction;
}
customRow.push(data);console.log("finished col "+(col+1)+" of "+cols);
}
customGrid.push(customRow);console.log("finished row "+(row+1)+" of "+rows);
}
console.log("Grid completed");
return customGrid;
}
函数调用如下所示:
var myGrid=buildGrid(3,3,function(){return buildGrid(2,2,buildSquare)});
buildSquare只是一个构造函数。
现在这是控制台日志:
evalresult[eval12][52]:
Let's see, we have an order for 3 rows, 3 cols and within each, function (){return buildGrid(2,2,buildSquare)}
evalresult[eval12][61]:
creating row 1 of 3
evalresult[eval12][63]:
creating col 1 of 3
evalresult[eval12][52]:
Let's see, we have an order for 2 rows, 2 cols and within each, function buildSquare(){counter++;return new Square();}
evalresult[eval12][61]:
creating row 1 of 2
evalresult[eval12][63]:
creating col 1 of 2
evalresult[eval12][73]:
finished col 1 of 2
evalresult[eval12][63]:
creating col 2 of 2
evalresult[eval12][73]:
finished col 2 of 2
evalresult[eval12][76]:
finished row 1 of 2
evalresult[eval12][61]:
creating row 2 of 2
evalresult[eval12][63]:
creating col 1 of 2
evalresult[eval12][73]:
finished col 1 of 2
evalresult[eval12][63]:
creating col 2 of 2
evalresult[eval12][73]:
finished col 2 of 2
evalresult[eval12][76]:
finished row 2 of 2
evalresult[eval12][78]:
Grid Completed
evalresult[eval12][73]:
finished col 3 of 3
evalresult[eval12][76]:
finished row 3 of 3
evalresult[eval12][78]:
Grid Completed
发现问题?首先启动较大的3x3函数,然后在'data = dataFunction();',开始调用内部2x2函数。一旦2x2函数完成,函数应该跳转到3x3网格的下一部分,而是返回网格不完整。我认为for循环变量(即'rows'和'cols')将与其小范围内的值绑定,并且内部2x2网格的FOR变量不会影响3x3网格中外部作用域的FOR变量。这是发生了什么事吗?
我在这里缺少什么?
非常感谢你们。
答案 0 :(得分:0)
您需要在函数内部使用var
声明变量“row”。就目前而言,变量是全局的,因此当对“buildGrid”进行嵌套调用时,代码将操纵同一个变量。
也使用var
声明“数据”。进入的一个好习惯是包括行
"use strict";
位于整个JavaScript块的顶部,或者如果这有问题,至少在您的函数顶部。这会将运行时置于“严格”模式,并且在该模式下,无法声明类似的变量会导致错误。