[英]Recursive “parsing” function in javascript
I'm trying to create a kind of recursive parsing function, but it does not work as it should. 我正在尝试创建一种递归解析函数,但是它不能正常工作。
The array to be parsed: 要解析的数组:
gridArray = [
{
type:"row",
text:"row1",
cols: [
{
type:"col",
text:"col1",
rows: [
{
type:"row",
text:"row1 nested",
cols: [{}]
}
]
},
{
type:"col",
text:"col2",
rows: [{}]
}
]
}
]
The function: 功能:
function createHtmlCode(gridArray,level){
for(var y=0; y<gridArray.length; y++){
obRow = gridArray[y];
r+="<div class='row'>";
arCol = obRow.cols;
for(var x=0; x<arCol.length; x++){
obCol = arCol[x];
r+="<div class='col'>";
if(obCol.rows){
createHtmlCode(obCol.rows,level++);
}
r+="</div>";
}
r+="</div>";
}
}
r="";
createHtmlCode(gridArray,1);
At the moment the result (r) is: 目前,结果(r)为:
<div class="row">
<div class="col">
<div class="row">
<div class="col">
</div>
</div>
</div>
</div>
... but it shoud be: ...但是应该是:
<div class="row">
<div class="col">
<div class="row">
<div class="col">
</div>
</div>
</div>
<div class="col">
<div class="row">
</div>
</div>
</div>
What am I doing wrong? 我究竟做错了什么? Thank you in advance for your tips! 预先感谢您的提示!
Hahaha! 哈哈哈! You have a very subtle (but very common) error. 您有一个非常微妙(但很常见)的错误。
See here: 看这里:
arCol = obRow.cols;
That's the bug, if you look closely. 如果您仔细观察的话,那就是错误。
Got it? 得到它了? Or you want me to spoil it? 还是要我宠坏它?
The error is: in Javascript, if you don't declare a variable as local, it defaults to global. 错误是:在Javascript中,如果不将变量声明为local,则默认为global。 arCol gets reset in the recursive call! arCol在递归调用中被重置!
All the variable declarations should be explicit: 所有变量声明都应该是明确的:
var arCol = obRow.cols;
Other tips: 其他提示:
x
and y
should be used to indicate spatial information (on the "x-axis" and "y-axis"); x
和y
应该用来表示空间信息(在“ x轴”和“ y轴”上); use i
and j
(and if necessary k
) for array indices. 使用i
和j
(必要时使用k
)作为数组索引。 And declare them as local. 并将它们声明为本地。 r
. 不要使用全局可变值-在这个例子中r
Instead have the function return the string 而是让函数返回字符串 gridArray
in this case) or a local variable. 绝对不要对全局变量和形式参数(在这种情况下为gridArray
)或局部变量使用相同的名称。 The computer will not be confused, but you will be. 不会混淆计算机,但是会。 So the corrected code would be 所以正确的代码将是
function createHtmlCode(grid,level){
var r = "";
for(var i=0; i<grid.length; i++){
r+="<div class='row'>";
var arCol = grid[i].cols;
for(var j=0; j<arCol.length; j++){
r+="<div class='col'>";
var rows = arCol[j].rows;
if(rows){
r += createHtmlCode(rows,level++);
}
r+="</div>";
}
r+="</div>";
}
return r;
}
console.log(createHtmlCode(myGrid,1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.