function toTree(rows){
function exists(rows, parentId){
for(var i=0; i<rows.length; i++){
if (rows[i].id == parentId) return true;
}
return false;
}
var nodes = [];
for(var i=0; i<rows.length; i++){
var row = rows[i];
if (!exists(rows, row.parentId)){
nodes.push({
id:row.id,
text:row.text,
state:'closed'
});
}
}
var toDo = [];
//如下的for循环 是把nodes数组对象的引用赋值给了toDo ,功能类似:toDo = nodes; 下面的操作修改了node的值,其实是修改了nodes中的元素的值.
for(var i=0; i<nodes.length; i++){
toDo.push(nodes[i]);
}
while(toDo.length){
var node = toDo.shift();
for(var i=0; i<rows.length; i++){
var row = rows[i];
if (row.parentId === node.id){
var child = {id:row.id,text:row.text,attributes:{href:row.href}};
// alert(JSON.stringify(node.children));
if (node.children){
node.children.push(child);
} else {
node.children = [child];
}
toDo.push(child);
}
}
}
return nodes; //最终结果是nodes的内容变化了.
}