当变量指向一个对象的时刻,现实指向的是存储地点
测试:
a = {val: 123}
b = a
b.val = 321
console.log(a)
// 效果:{val: 321}
数组转树的体式格局:
arr = [
{id: 1, name: '节点1', pid: 0},
{id: 2, name: '节点2', pid: 1},
{id: 3, name: '节点3', pid: 1},
{id: 4, name: '节点4', pid: 2},
{id: 5, name: '节点5', pid: 1},
{id: 6, name: '节点6', pid: 3},
{id: 7, name: '节点7', pid: 4},
{id: 8, name: '节点8', pid: 2}
];
function node(d){
return {
name: d.name,
id: d.id,
pid: d.pid,
children: []
}
}
function tree(arr){
var narr = {};
for (var i in arr) { // 将id作为键值轻易二次遍历做索引
narr[arr[i].id] = node(arr[i]);
}
for (var j in narr) {
if(typeof narr[narr[j].pid] != 'undefined'){
narr[narr[j].pid].children.push(narr[j])
}
}
return narr[1] // id为1的是根节点
}
console.log(tree(arr))
如许只需遍历俩次
第一次遍历将数组转节点对象,存储到新的对象里,id为键值轻易索引
第二次遍历依据索引插进去子节点